使用 FlatMap 迭代器时,为什么我会收到错误 FromIterator<&{integer}> is not implementation for Vec<i32> ?

att*_*ona 9 rust

考虑这个片段:

fn main() {
    let arr_of_arr = [[1, 2], [3, 4]];
    let res = arr_of_arr
        .iter()
        .flat_map(|arr| arr.iter())
        .collect::<Vec<i32>>();
}
Run Code Online (Sandbox Code Playgroud)

编译器错误是:

fn main() {
    let arr_of_arr = [[1, 2], [3, 4]];
    let res = arr_of_arr
        .iter()
        .flat_map(|arr| arr.iter())
        .collect::<Vec<i32>>();
}
Run Code Online (Sandbox Code Playgroud)

为什么这段代码不能编译?

特别是,我无法理解错误消息:什么类型代表&{integer}

DK.*_*DK. 8

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

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

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>>();
}
Run Code Online (Sandbox Code Playgroud)

  • 在 Rust 1.53 之前,数组上的“inter_iter()”被实现为切片器迭代器(如“iter()”);因此,它不会产生拥有的价值。2015/2018 版本中仍然存在这种行为。我无法告诉你我花了多少时间试图解决某个 bug 到底发生了什么,只是为了意识到我需要阅读有关数组的文档。https://doc.rust-lang.org/std/primitive.array.html#editions (2认同)