【问题标题】:Iterator collect issue with value of type `Vec<String>` cannot be built from `Iterator<Item=&String>` [duplicate]无法从 `Iterator<Item=&String>` 构建类型为 `Vec<String>` 的迭代器收集问题 [重复]
【发布时间】:2020-05-01 21:26:00
【问题描述】:

我在使用 Iteratorflat_map 函数时遇到了困难,我不太清楚如何理解和解决这个编译器错误。

我通过序列化两个结构将文件路径列表平面映射为两个字符串:

let body: Vec<String> = read_dir(query.to_string())
    .iter()
    .enumerate()
    .flat_map(|(i, path)| {
        let mut body: Vec<String> = Vec::with_capacity(2);

        let entry = Entry { i };
        body.push(serde_json::to_string(&entry).unwrap());

        let record = parse_into_record(path.to_string()).unwrap();
        body.push(serde_json::to_string(&record).unwrap());

        body.iter()
    })
    .collect();
error[E0277]: a value of type `std::vec::Vec<std::string::String>` cannot be built from an iterator over elements of type `&std::string::String`
   --> src/main.rs:275:10
    |
275 |         .collect();
    |          ^^^^^^^ value of type `std::vec::Vec<std::string::String>` cannot be built from `std::iter::Iterator<Item=&std::string::String>`
    |
    = help: the trait `std::iter::FromIterator<&std::string::String>` is not implemented for `std::vec::Vec<std::string::String>`

【问题讨论】:

标签: rust iterator


【解决方案1】:

iter 为您提供了引用的迭代器。您需要一个拥有其值的消费迭代器。为此,请改用into_iter。这是一个简单的例子:

fn main() {
    let result = (0..10).flat_map(|_| {
       let vec: Vec<String> = vec!["a".into(), "b".into(), "c".into()];
       vec.into_iter()
    }).collect::<Vec<_>>();
}

iterinto_iter的区别详细解释,参考下面的回答What is the difference between iter and into_iter?

【讨论】:

  • 现在我了解了这一点,我了解了我一直遇到的许多其他问题。谢谢!
猜你喜欢
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
  • 2015-09-02
  • 1970-01-01
  • 2021-03-16
  • 2015-11-28
  • 2020-09-11
相关资源
最近更新 更多