Shorthand for copying into a mutable iterator

I have an iter_mut() and I'd like to use it to overwrite the underlying data from another iterator.

iter_to.for_each(|x| *x = *;

Is there a shorthand notation for this?


Use zip like this: to.iter_mut().zip(iter_from).for_each(|(to, from)| *to = from)

1 Like

I was going to suggest the same. However for completeness note that there is a slight difference… the original code panics when the iter_to is longer than iter_from, while the zip solution will not panic, but simply leave the parts of iter_to beyond the length of iter_from unmodified.

Assuming that what might actually be wanted here is that both iterators must have the same length, the zip_eq method from the itertools crate might be useful.


Thanks both, impressively quick and comprehensive responses.

Both solutions let me get rid of the preceding let statement for creating iter_from, which is great. I went with #1 just because it did not pull in itertools, although it is a good point about not panicking when iter_from is shorter.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.