Hi,
I am also having the same issue documented here:
Can anyone offer an explanation why you must iterate twice? I am new and cannot reason about this, thank you!
Hi,
I am also having the same issue documented here:
Can anyone offer an explanation why you must iterate twice? I am new and cannot reason about this, thank you!
It's because push
could reallocate the vector, which would make any existing references point at the wrong thing. However, once everything is pushed, you know the locations in memory wont change anymore.
Note that you can still do stuff like this:
fn main() {
let mut vec = vec![0; 1024];
let mut refs: Vec<&i32> = Vec::new();
let mut counter = 0;
for mut_ref in vec.iter_mut() {
*mut_ref = counter;
counter += 1;
refs.push(&*mut_ref);
}
println!("{:?}", refs);
}
but wasn't everything already "pushed" into the original? I don't see the difference between original and new I guess. THanks for the quick answer! I'm sure it's right I'm just missing the understanding still.
Sure, but they wanted references that point into new
, and new
did not have everything pushed yet.
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.