Swap two mutable references

Hi Rust fam,
I have two mutable references, each references a different Vec. Im mutable borrowing them in a loop so I can keep reusing them. Objective being: no allocation during iterations.

I'll let my code do the talking:

let mut first = vec![0, 10]
let mut second = vec![0, 10]

for i in 1..50 {
    let mut ref_first = &mut first;
    let mut ref_second = &mut second;
    borrow_both_and_change_contents_of_second(ref_first, ref_second);
        Here is where I would like my ref_first refer second vec so I can clear first. 
        This way I can keep reusing two vecs in for loop without allocation.
    reset_all_values_to_0(&mut first)

I have tried using temp which points to first but I keep running in to borrow errors and all seem valid.

At this point Im wondering if this is even possible. Again, the objective is not to allocate every iteration.

Don't bother with ref_first and ref_second, just swap the vectors directly -- a Vec already contains indirection to the heap, so this is cheap:

std::mem::swap(&mut first, &mut second);

F%*&^#( me.
That works!!

Im just curious. What does "indirection" mean?

a Vec already contains indirection to the heap

It means that the Vec struct doesn't contain the data directly, it just contains a pointer to the data. So when you swap the two Vecs, you're not moving the actual data in memory, you're just swapping the pointers (and sizes, and capacities).

Great. Im so glad these things are available in Rust out of the box.

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.