有没有一种方法可以直接消耗人造丝链而不先收集它?

时间:2018-07-22 13:11:35

标签: rust 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`

playground

1 个答案:

答案 0 :(得分:4)

您正在寻找ParallelIterator::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);
    });
}

相关:

另请参阅: