HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

How to get a slice as an array in Rust?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayhowslicerustget

Problem

I have an array of an unknown size, and I would like to get a slice of that array and convert it to a statically sized array:

fn pop(barry: &[u8]) -> [u8; 3] {
    barry[0..3] // expected array `[u8; 3]`, found slice `[u8]`
}


How would I do this?

Solution

You can easily do this with the TryInto trait (which was stabilized in Rust 1.34):
// Before Rust 2021, you need to import the trait:
// use std::convert::TryInto;

fn pop(barry: &[u8]) -> [u8; 3] {
barry.try_into().expect("slice should have length 3")
}


But even better: there is no need to clone/copy your elements! It is actually possible to get a &[u8; 3] from a &[u8]:
fn pop(barry: &[u8]) -> &[u8; 3] {
barry.try_into().expect("slice should have length 3")
}


As mentioned in the other answers, you probably don't want to panic if the length of barry is not 3, but instead handle this error gracefully.

This works thanks to these impls of the related trait TryFrom (before Rust 1.47, these only existed for arrays up to length 32):
impl TryFrom for [T; N]
where
T: Copy,

impl TryFrom for &'a [T; N]

impl TryFrom for &'a mut [T; N]

Context

Stack Overflow Q#25428920, score: 203

Revisions (0)

No revisions yet.