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

我的未来我决定 提交于 2020-02-03 08:03:54

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/49727495/why-do-i-get-the-error-fromiteratorinteger-is-not-implemented-for-veci32

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!