#iterator #clone #object #zip #cloning #iteration #cloned

zip_clone

Zip an iterator to a repeately cloned object

2 releases

0.1.1 Jun 18, 2024
0.1.0 Apr 20, 2024

#807 in Rust patterns

Download history 7/week @ 2024-07-27 2/week @ 2024-08-03 1/week @ 2024-08-10 5/week @ 2024-08-24 7/week @ 2024-08-31 10/week @ 2024-09-07 38/week @ 2024-09-14 33/week @ 2024-09-21 122/week @ 2024-09-28 58/week @ 2024-10-05 62/week @ 2024-10-12 107/week @ 2024-10-19 52/week @ 2024-10-26 68/week @ 2024-11-02

301 downloads per month
Used in 3 crates (via typle)

MIT/Apache

9KB
172 lines

zip_clone

Zip an iterator to a repeately cloned object.

Pass an owned object that implements Clone to create an iterator that zips the original iterator with clones of the object.

One iteration returns the original object, hence using one fewer clones than iter.zip(repeat_with(|| cloned.clone())).

This is useful for loops where a value is cloned for each iteration, but is not used after the iteration.

Instead of cloning a value 10 times using:

let mut v = vec![];
let s = String::from("Hello");
for _ in 0..10 {
    v.push(s.clone());
}

clone the value 9 times using:

use zip_clone::ZipClone as _;

let mut v = vec![];
let s = String::from("Hello");
for (_, s) in (0..10).zip_clone(s) {
    v.push(s);
}

The object may be cloned even fewer times if items are skipped. For example, last() consumes the iterator but returns the last value without cloning the object for intermediate values:

use zip_clone::ZipClone as _;

let mut v = vec![];
let s = String::from("Hello");
v.push((0..10).zip_clone(s).last());

No runtime deps