gpt4 book ai didi

rust - 无法从 `Vec` 构建类型为 `Iterator` 的值的迭代器收集问题

转载 作者:行者123 更新时间:2023-12-03 11:25:47 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What is an idiomatic way to collect an iterator of &T into a collection of Ts?

(2 个回答)



Type issue with Iterator collect

(2 个回答)



Why do I get the error FromIterator<&{integer}> is not implemented for Vec<i32> when using a FlatMap iterator?

(1 个回答)


去年关闭。




我在使用 Iterator 时遇到困难的 flat_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();
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>`

最佳答案

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

详细解释 iter之间的区别和 into_iter ,引用以下回答 What is the difference between iter and into_iter?

关于rust - 无法从 `Vec<String>` 构建类型为 `Iterator<Item=&String>` 的值的迭代器收集问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59745873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com