Reputation: 788
There seem to be two ways to try to turn a vector into an array, either via a slice (fn a
) or directly (fn b
):
use std::array::TryFromSliceError;
use std::convert::TryInto;
type Input = Vec<u8>;
type Output = [u8; 1000];
// Rust 1.47
pub fn a(vec: Input) -> Result<Output, TryFromSliceError> {
vec.as_slice().try_into()
}
// Rust 1.48
pub fn b(vec: Input) -> Result<Output, Input> {
vec.try_into()
}
Practically speaking, what's the difference between these? Is it just the error type? The fact that the latter was added makes me wonder whether there's more to it than that.
Upvotes: 5
Views: 1298
Reputation: 60022
They have slightly different behavior.
The slice to array implementation will copy the elements from the slice. It has to copy instead of move because the slice doesn't own the elements.
The Vec
to array implementation will consume the Vec
and move its contents to the new array. It can do this because it does own the elements.
Upvotes: 10