考虑这个片段:
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}
是编译器在知道某些内容具有整数类型但不知道时使用的占位符which整数类型。
问题是您试图将“整数引用”序列收集到“整数”序列中。要么更改为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>>();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)