Does cloning an iterator do the entire base vector?

I would like to iterate over a vector multiple times:

let my_vector = vec![1, 2, 3, 4, 5];
let mut out_vector = vec![];
for i in my_vector {
    for j in my_vector {
        out_vector.push(i * j + i + j);
    }
}

      

j-loop has a "value used here after move" error. I know I can place &

in front of two my_vector

and borrow vectors, but it's nice to have multiple ways to do things. I would also like to understand a little.

Alternatively, I can write the following:

let i_vec = vec![1, 2, 3, 4, 5, 6];
let iterator = i_vec.iter();
let mut out_vec = vec![];
for i in iterator.clone() {
    for j in iterator.clone() {
        out_vec.push(i * j + i + j);
    }
}

      

I looked at What is the most efficient way to reuse an iterator in Rust? :

Iterators in general are Clone-able if all of their "parts" are Clone-able.

Is the actual allocated data heap a "chunk" of the iterator, or does the memory address point to the heap data of the aforementioned part?

+3


source to share


1 answer


Cloning a slice iterator (which is the type of iterator you get when you call iter()

in Vec

or on an array) does not copy the underlying data. Both iterators still point to the data stored in the original vector, so the cloning operation is cheap.

The same is true for cloned iterators for other types.

In your case, instead of calling i_vec.iter()

and then cloning it, you can also call i_vec.iter()

multiple times:



for i in i_vec.iter() {
    for j in i_vec.iter() {

      

which gives the same result, but is probably more readable.

+3


source







All Articles