Convert Vec to Array with TryFrom


I'm having trouble converting a vector that I know is of size 32 to an array.

Here is some sample playground code that is erroring:

It says the trait bound [T; 32]: std::convert::TryFrom<&[T]> is not satisfied, but that doesn't seem to be right according to this documentation:<%26'_%20[T]>

I was following this StackOverflow post originally:

Any help will be much appreciated! Thank you!


It requires that the type T implement the Copy trait.

fn demo<T>(v: Vec<T>) -> [T; 32] where T: Copy {
    let slice = v.as_slice();
    let array: [T; 32] = match slice.try_into() {
        Ok(ba) => ba,
        Err(_) => panic!("Expected a Vec of length {} but it was {}", 32, v.len()),

Next release you'll be able to go directly from a Vec<T>, without needing T: Copy:<Vec<T>>


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.