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>` |
为什么此代码段无法编译?
特别是,我无法理解错误消息:哪种类型表示
问题是您试图将"整数引用"序列收集到"整数"序列中。更改为
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>>(); } |