首先,阅读。然后...
审查实施者IntoParallelIterator:
impl<'data, T: Sync + 'data> IntoParallelIterator for &'data [T]
添加Sync
绑定解决了这个问题。 Rayon 的工作方式可能是使用多个线程,但是您原来的T
不保证共享或线程之间是否安全!这又出现了第二次:
error: no method named `collect` found for type `rayon::par_iter::map::Map<rayon::par_iter::slice::SliceIter<'_, T>, rayon::par_iter::map::MapFn<[closure@src/main.rs:7:27: 7:39]>>` in the current scope
--> src/main.rs:7:41
|
7 | floats.par_iter().map(|f| f.sqrt()).collect()
| ^^^^^^^
|
= note: the method `collect` exists but the following trait bounds were not satisfied: `rayon::par_iter::map::MapFn<[closure@src/main.rs:7:27: 7:39]> : rayon::par_iter::map::MapOp<&_>`, `rayon::par_iter::map::Map<rayon::par_iter::slice::SliceIter<'_, T>, rayon::par_iter::map::MapFn<[closure@src/main.rs:7:27: 7:39]>> : std::iter::Iterator`
退房collect:
fn collect<C>(self) -> C
where C: FromParallelIterator<Self::Item>
我们可以看到目标类型需要实现FromParallelIterator:
impl<T> FromParallelIterator<T> for Vec<T> where T: Send
因此,添加两个边界可以使其编译:
fn sqrts<T: Float + Send + Sync>(floats: &[T]) -> Vec<T>