Consider this snippet:
fn main() {
let arr_of_arr = [[1, 2], [3, 4]];
let res = arr_of_arr
.iter()
.flat_map(|arr| arr.iter())
.collect::<Vec<i32>>();
}
The compiler error is:
error[E0277]: the trait bound `std::vec::Vec<i32>: std::iter::FromIterator<&{integer}>` is not satisfied
--> src/main.rs:6:10
|
6 | .collect::<Vec<i32>>();
| ^^^^^^^ a collection of type `std::vec::Vec<i32>` cannot be built from an iterator over elements of type `&{integer}`
|
= help: the trait `std::iter::FromIterator<&{integer}>` is not implemented for `std::vec::Vec<i32>`
Why does this snippet not compile?
In particular, I'm not able to understand the error messages: what type represents &{integer}
?
{integer}
is a placeholder the compiler uses when it knows something has an integer type, but not which integer type.
The problem is that you're trying to collect a sequence of "references to integer" into a sequence of "integer". Either change to Vec<&i32>
, or dereference the elements in the iterator.
fn main() {
let arr_of_arr = [[1, 2], [3, 4]];
let res = arr_of_arr.iter()
.flat_map(|arr| arr.iter())
.cloned() // or `.map(|e| *e)` since `i32` are copyable
.collect::<Vec<i32>>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With