Is there a vector append that consumes the second vector?

After

let mut a = vec![1,2,3];
let mut b = vec![4,5];

a.append(&mut b);

b is empty, but it still exists.

I have come to love this characteristic of Rust that variables that shouldn't be used anymore are actually gone and I have found that most library functions come in a flavor that consumes (moves) their input values. Because of that a.append(&mut b) feels a bit strange. Is there an a.append(b) that I'm just not seeing or is there a particular reason against having that?

If your goal is to keep the memory of b around with the same capacity, you can use the drain method and pass the result to extend.

a.extend(b.drain(..)) should work

1 Like

No, quite the opposite, I want b gone. I now realized I could just do

a.append(&mut b);
std:mem:drop(b);

to tell myself that b is not useful anymore.

And if b is a temporary instead of a variable it is dropped there anyway.

I see. I'm on my phone, so a bit slow to read the docs, so I didn't realize what append actually does. You could also use a.extend(b) to consume b.

5 Likes

Indeed, b becomes an iterator automatically.

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.