-
I am using rayon::par_iter, and I have an
x: Vec<T>
-
Normally, I can do
x.par_iter().map(...).collect()
which processes all elements. However, I only want to process the firstn
elements (without truncatingx
itself to n elements). -
Question:Without truncating
x
itself ton
elements, is there a way topar_iter
over only the firstn
elements ?
It can run on a slice too;
x[0..n].par_iter()
Yes, a slice will do this. FWIW, I think x[..n]
is more idiomatic, but there's no semantic difference.
You can also .take(n)
on any IndexedParallelIterator
. This might be preferable if you're not sure that your source actually has at least n
elements, otherwise slicing will panic out of bounds.
You mean x.par_iter().take(n)
?
If so, the 'laziness' of iters always confuses me, as intuitively, I imagine a 'fork' happening at the par_iter()
step, and thus the take(n)
makes no sense. However, given we're just "building up up a computation graph", and executing it later at collect()
, then this makes sense.
iter
should be renamed placeholder_to_do_stuff_later
Yes, and you're right that laziness means nothing starts on the threadpool here yet.