nirvan
October 28, 2020, 12:56am
1
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:
I was following this StackOverflow post originally:
https://stackoverflow.com/questions/25428920/how-to-get-a-slice-as-an-array-in-rust
Any help will be much appreciated! Thank you!
nirvan
October 28, 2020, 1:13am
2
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
: TryFrom in std::convert - Rust
4 Likes
system
Closed
January 26, 2021, 1:16am
4
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.