请考虑以下代码片段:
fn main() {
let arr_of_arr = [[1, 2], [3, 4]];
let res = arr_of_arr
.iter()
.flat_map(|arr| arr.iter())
.collect::<Vec<i32>>();
}
编译器错误为:
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>
,或取消引用迭代器中的元素。
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>>();
}