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] // mismatched types: expected `[u8, ..3]` but found `&[u8]`
}
How would I do this?
I recommend using the crate arrayref, which has a handy macro for doing just this.
Note that, using this crate, you create a reference to an array,
&[u8; 3]
, because it doesn't clone any data!If you do want to clone the data, then you can still use the macro, but call clone at the end:
or
Here's a function that matches the type signature you asked for.
But since
barry
could have fewer than three elements, you may want to return anOption<[u8; 3]>
rather than a[u8; 3]
.This answer uses the unstable
try_from
feature!You can easily do this with the brand new
TryInto
trait (which is still unstable as of June 2018):But even better: there is no need to clone your array! It is actually possible to get a
&[u8; 3]
from a&[u8]
:As mentioned in the other answers, you probably don't want to panic if the length of
barry
is not 3, so you should return anOption<[u8; 3]>
or something similar to handle this error gracefully.This works thanks to these impls (where
$N
is just an integer between 1 and 32) of the related traitTryFrom
:You can create a custom macro to solve the issue. The constraint here, you have to specify slice size as constant. You can not create array with dynamic length which is explained on these questions:
For working code: playground
Thanks to @malbarbo we can use this helper function:
to get a much neater syntax:
as long as
T: Default + Clone
.If you know your type implements
Copy
, you can use this form:Both variants will
panic!
if the target array and the passed-in slice do not have the same length.You can manually create the array and return it.
Here is a function that can easily scale if you want to get more (or less) than 3 elements.
Note that if the slice is too small, the end terms of the array will be 0's.