Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get the error FromIterator<&{integer}> is not implemented for Vec<i32> when using a FlatMap iterator?

Tags:

rust

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}?

like image 714
attdona Avatar asked Apr 09 '18 07:04

attdona


1 Answers

{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>>();
}
like image 199
DK. Avatar answered Sep 22 '22 19:09

DK.