无法从 `Iterator<Item=&String>` 构建类型为 `Vec<String>` 的值的迭代器收集问题

Mir*_*asi 7 iterator rust

我在使用Iterator'sflat_map函数时遇到了困难,我不太确定如何理解和解决这个编译器错误。

我通过序列化两个结构将文件路径列表 flat_mapping 成两个字符串:

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();
Run Code Online (Sandbox Code Playgroud)
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>`
Run Code Online (Sandbox Code Playgroud)

ssh*_*124 11

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<_>>();
}
Run Code Online (Sandbox Code Playgroud)

iter和之间的区别的详细解释into_iter,请参考下面的回答iter 和 into_iter 有什么区别?

  • 现在我明白了这一点,我也明白了我一直遇到的很多其他问题。谢谢你! (2认同)

归档时间:

查看次数:

7629 次

最近记录:

6 年,1 月 前