【问题标题】:Why do I get the error FromIterator<&{integer}> is not implemented for Vec<i32> when using a FlatMap iterator?为什么我在使用 FlatMap 迭代器时收到错误 FromIterator<&{integer}> is not implemented for Vec<i32>?
【发布时间】:2018-04-09 07:20:49
【问题描述】:

考虑一下这个sn-p:

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>`

为什么这个 sn-p 编译不出来?

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

【问题讨论】:

标签: rust


【解决方案1】:

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

问题是您试图将“对整数的引用”序列收集到“整数”序列中。要么更改为Vec&lt;&amp;i32&gt;,要么取消引用迭代器中的元素。

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>>();
}

【讨论】:

  • 谁能解释为什么|arr| arr.into_iter()(而不是.clone())不起作用?我认为into_iter 会产生拥有的值而不是引用,但似乎并非如此?
  • 在 Rust 1.53 之前,数组上的 inter_iter() 被实现为切片器迭代器(如 iter());因此,它不会产生自有值。这种行为仍然存在于 2015/2018 版本中。我无法告诉你我花了多少时间试图围绕 wtf 解决某个错误,只是为了意识到我需要阅读有关数组的文档。 doc.rust-lang.org/std/primitive.array.html#editions
猜你喜欢
  • 2023-01-09
  • 1970-01-01
  • 2012-09-26
  • 2021-09-08
  • 1970-01-01
  • 1970-01-01
  • 2016-11-17
  • 2021-03-13
  • 2019-09-17
相关资源
最近更新 更多