我使用 Rayon 来产生相当大的返回值。将所有返回值收集到一个中时,这会使用大量内存Vec
。有没有办法避免创建Vec
并直接作为可迭代对象使用?
这是一个不起作用的示例:
fn main() {
let numbers: Vec<_> = "12.03 0.3 44.2 45 zzz".split_whitespace().collect();
let x = numbers
.par_iter()
.map(|n| n.parse::<f32>())
.filter_map(|n| n.ok());
for n in x {
println!("{:?}", n);
}
}
error[E0277]: the trait bound `rayon::iter::FilterMap<rayon::iter::Map<rayon::slice::Iter<'_, &str>, [closure@src/main.rs:10:14: 10:34]>, [closure@src/main.rs:11:21: 11:31]>: std::iter::Iterator` is not satisfied
|
13 | for n in x {
| ^ `rayon::iter::FilterMap<rayon::iter::Map<rayon::slice::Iter<'_, &str>, [closure@src/main.rs:10:14: 10:34]>, [closure@src/main.rs:11:21: 11:31]>` is not an iterator; maybe try calling `.iter()` or a similar method
|
= help: the trait `std::iter::Iterator` is not implemented for `rayon::iter::FilterMap<rayon::iter::Map<rayon::slice::Iter<'_, &str>, [closure@src/main.rs:10:14: 10:34]>, [closure@src/main.rs:11:21: 11:31]>`
= note: required by `std::iter::IntoIterator::into_iter`
您正在寻找ParallelIterator::for_each https://docs.rs/rayon/1.0.2/rayon/iter/trait.ParallelIterator.html#method.for_each:
extern crate rayon; // 1.0.2
use rayon::prelude::*;
fn main() {
let numbers = ["12.03", "0.3", "44.2", "45", "zzz"];
let x = numbers.par_iter().flat_map(|n| n.parse::<f32>());
x.for_each(|n| {
println!("{:?}", n);
});
}
Related:
- ParallelIterator::for_each_with https://docs.rs/rayon/1.0.2/rayon/iter/trait.ParallelIterator.html#method.for_each_with
- ParallelIterator::try_for_each https://docs.rs/rayon/1.0.2/rayon/iter/trait.ParallelIterator.html#method.try_for_each
- ParallelIterator::try_for_each_with https://docs.rs/rayon/1.0.2/rayon/iter/trait.ParallelIterator.html#method.try_for_each_with
也可以看看:
- 如何满足迭代器特征界限才能在这里使用 Rayon? https://stackoverflow.com/q/42721458/155423
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)