Does cloning an iterator copy the entire underlying vector?

Viewed 2089

I would like to iterate over a vector several 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);
    }
}

The j-loop has a "value used here after move" error. I know that I can place an & before the two my_vectors and borrow the vectors, but it is nice to have more than one way to do things. I would like a little insight as well.

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's the most efficient way to reuse an iterator in Rust?:

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

Is the actual heap allocated data a "piece" of the iterator or is it the memory address that points to the heap data the aforementioned piece?

1 Answers
Related