[英]Why do I get the error FromIterator<&{integer}> is not implemented for Vec<i32> when using a FlatMap iterator?
Consider this snippet: 请考虑以下代码段:
fn main() {
let arr_of_arr = [[1, 2], [3, 4]];
let res = arr_of_arr
.iter()
.flat_map(|arr| arr.iter())
.collect::<Vec<i32>>();
}
The compiler error is: 编译器错误是:
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>`
Why does this snippet not compile? 为什么这个代码片段无法编译?
In particular, I'm not able to understand the error messages: what type represents &{integer}
? 特别是,我无法理解错误消息:什么类型代表
&{integer}
?
{integer}
is a placeholder the compiler uses when it knows something has an integer type, but not which integer type. {integer}
是编译器在知道某些内容具有整数类型但不知道哪种整数类型时使用的占位符。
The problem is that you're trying to collect a sequence of "references to integer" into a sequence of "integer". 问题是你试图将一系列“对整数的引用”收集到一个“整数”序列中。 Either change to
Vec<&i32>
, or dereference the elements in the iterator. 要么更改为
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>>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.