How to collect iterator elements into a fixed-size array in Rust?
Hi everyone! I recently started learning Rust and encountered a problem that seems very simple, but I can't find the right solution.
\n\nI have an iterator that returns a sequence of numbers. I want to collect all these numbers into an array [i32; N], where N is known at compile time. For example, I'm writing a function that takes a slice of numbers and returns an array of the first 5 elements:
fn first_five(data: &[i32]) -> [i32; 5] {\n data.iter().take(5).collect() // doesn't work!\n}\n\nThe compiler gives an error: the trait bound `[i32; 5]: FromIterator<&i32>` is not satisfied. I understand that collect() works with collections like Vec, but how do I make it work with arrays?
I tried
No answers yet.
Log in to leave an answer