关于rust:为什么会收到错误FromIterator <

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

请考虑以下代码段:

1
2
3
4
5
6
7
fn main() {
    let arr_of_arr = [[1, 2], [3, 4]];
    let res = arr_of_arr
        .iter()
        .flat_map(|arr| arr.iter())
        .collect::<Vec<i32>>();
}

编译器错误为:

1
2
3
4
5
6
7
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>`

为什么此代码段无法编译?

特别是,我无法理解错误消息:哪种类型表示&{integer}


{integer}是当编译器知道某事物具有整数类型而不是整数类型时使用的占位符。

问题是您试图将"整数引用"序列收集到"整数"序列中。更改为Vec<&i32>或取消引用迭代器中的元素。

1
2
3
4
5
6
7
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>>();
}