简体   繁体   English

使用 Rayon into_par_iter().sum() 和自定义结构

[英]Using Rayon into_par_iter().sum() with custom struct

I'm trying to get use Rayon::prelude::into_par_iter to sum up a bunch of instances of a struct.我正在尝试使用 Rayon::prelude::into_par_iter 来总结结构的一堆实例。 I've implemented std::iter::Sum for the struct, but am still running into an error.我已经为结构实现了std::iter::Sum ,但仍然遇到错误。 Here is my example code;这是我的示例代码;

use std::iter::Sum;

use rayon::prelude::*;

pub struct TestStruct {
    val: f32,
}

impl TestStruct {
    pub fn new(v: f32) -> Self {
        Self { val: v }
    }
}

impl<'a> Sum<&'a Self> for TestStruct {
    fn sum<I>(iter: I) -> Self
    where
        I: Iterator<Item = &'a Self>,
    {
        iter.fold(Self { val: 0. }, |a, b| Self {
            val: a.val + b.val,
        })
    }
}

fn main() {
    let default_val: f32 = 1.1;
    let sum: TestStruct = (0..5).into_par_iter().map(|&default_val| {
        TestStruct::new(default_val)
    })
    .sum();

    println!("{}", sum.val);
}

and I am told the trait 'std::iter::Sum' is not implemented for 'TestStruct' , but I think I am implementing it.我被告知the trait 'std::iter::Sum' is not implemented for 'TestStruct' ,但我想我正在实现它。 Am I missing something here?我在这里错过了什么吗?

Two small compounded issues.两个复杂的小问题。 One is that the std::iter::Sum is defined as:一种是std::iter::Sum定义为:

pub trait Sum<A = Self> {
    fn sum<I>(iter: I) -> Self
    where
        I: Iterator<Item = A>;
}

The Self here refers to whatever the struct gets the implementation and the default generic parameter has already been filled in. You don't need to specify it any more if implementing Sum for struct itself.这里的Self指的是 struct 获取实现的任何内容,并且已经填充了默认的泛型参数。如果为 struct 本身实现Sum ,则不需要再指定它。

The other is that the map closure parameter default_val , which is an integer, shadows the previous float one with the same name.另一个是map闭包参数default_val ,它是一个整数,遮蔽了前一个具有相同名称的浮点数。 Since TestStruct::new expects a f32 , it leads to a type error.由于TestStruct::new需要f32 ,因此会导致类型错误。

This works:这有效:

impl Sum for TestStruct {
    fn sum<I>(iter: I) -> Self
    where
        I: Iterator<Item = Self>,
    {
        ...
    }
}

fn main() {
    let default_val: f32 = 1.1;
    let sum: TestStruct = (0..5)
        .into_par_iter()
        .map(|_| TestStruct::new(default_val))
        .sum();

    println!("{}", sum.val);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM