This question already has an answer here:
- How to get a slice as an array in Rust? 6 answers
Is there a good way to convert a Vec<T>
with size S
to an array of type [T; S]
? Specifically, I'm using a function that returns a 128-bit hash as a Vec<u8>
, which will always have length 16, and I would like to deal with the hash as a [u8, 16]
.
Is there something built-in akin to the as_slice
method which gives me what I want, or should I write my own function which allocates a fixed-size array, iterates through the vector copying each element, and returns the array?
Yes, this is what you should do.
It wouldn't really make sense to have a method on a vector to provide this, as you currently can't parameterize over an array's length. That would mean that each size would need to be a specialized implementation (although macros would help the boilerplate). Additionally, arrays must be completely initialized, so you quickly run into concerns about what to do when you convert a vector with too many or too few elements into an array.
For completeness, here is a small example of how it could look:
If your type doesn't implement
Copy
, you can't usecopy_from_slice
, so you'd have to useclone_from_slice
instead.