Is there a good way to convert a Vec to an arra

2019-01-12 08:17发布

This question already has an answer here:

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?

标签: rust
1条回答
冷血范
2楼-- · 2019-01-12 09:22

[S]hould 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:

fn from_slice(bytes: &[u8]) -> [u8; 32] {
    let mut array = [0; 32];
    let bytes = &bytes[..array.len()]; // panics if not enough data
    array.copy_from_slice(bytes); 
    array
}

If your type doesn't implement Copy, you can't use copy_from_slice, so you'd have to use clone_from_slice instead.

查看更多
登录 后发表回答