Convert Vec to Array with TryFrom

Hello!

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:

https://doc.rust-lang.org/std/convert/trait.TryFrom.html#impl-TryFrom<%26'_%20[T]>

I was following this StackOverflow post originally:

Any help will be much appreciated! Thank you!

Solved!

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()),
    };
    array
}

Next release you'll be able to go directly from a Vec<T>, without needing T: Copy: https://doc.rust-lang.org/beta/std/convert/trait.TryFrom.html#impl-TryFrom<Vec<T>>

4 Likes