【发布时间】:2020-05-01 21:26:00
【问题描述】:
我在使用 Iterator 的 flat_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>`
【问题讨论】:
-
将
body.iter()替换为body.into_iter()。请阅读minimal reproducible example。你的代码看起来也很奇怪