< 返回版块

hzqd 发表于 2021-03-24 00:59

Tags:rayon,type,parallel

以下代码可以通过编译:

use rayon::iter::IntoParallelRefIterator;

fn main() {
    (&vec![1,2,3]).par_iter();
}

我不理解为何下述代码无法通过编译:

use rayon::prelude::*;

trait VecExt<T, R> {
    fn map(&self, f: impl Fn(&T) -> R) -> Vec<R>;
}

impl<T, R> VecExt<T, R> for Vec<T> {
    fn map(&self, f: impl Fn(&T) -> R) -> Vec<R> {
        self.par_iter().map(f).collect()
    }
}

获得错误信息:

no method named `par_iter` found for reference `&Vec<T>` in the current scope
the method `par_iter` exists but the following trait bounds were not satisfied:
`&Vec<T>: IntoParallelIterator`
which is required by `Vec<T>: rayon::iter::IntoParallelRefIterator`
`&&Vec<T>: IntoParallelIterator`
which is required by `&Vec<T>: rayon::iter::IntoParallelRefIterator`
`&[T]: IntoParallelIterator`
which is required by `[T]: rayon::iter::IntoParallelRefIterator`

评论区

写评论
tyan-boot 2021-03-24 09:34
use rayon::prelude::*;

trait VecExt<T, R> {
    fn map(&self, f: impl Fn(&T) -> R + Sync + Send) -> Vec<R>;
}

impl<T, R> VecExt<T, R> for Vec<T>
where
    T: Sync,
    R: Send,
{
    fn map(&self, f: impl Fn(&T) -> R + Sync + Send) -> Vec<R> {
        self.par_iter().map(f).collect()
    }
}

少了Sync和Send的约束

1 共 1 条评论, 1 页