Search code examples
rustvectormemory-management

Moving all the contents of one vector into a new vector


To make a new vector with the content of an old vector (which I want to be emptied) I'm going to use:

foo.bar = my_vector.drain(0..).collect();

Is this idiomatic Rust?

Is the drain() optimised away, and the original vector's memory just given to the new vector?

Or is every element copied one-by-one into a fresh heap allocation?


Solution

  • I would do

    foo.bar = std::mem::take(&mut my_vector);
    

    This is a more general solution.

    std::mem::take() mutates its parameter in order to steal its content and leave it in its default state. The stolen content is used to create a new value of the same type.

    The actual stealing operation is a simple byte swap of the structure itself (a few pointers/integers for a Vec, a String, any other container...). The stored elements, which are probably heap-allocated, stay in place, thus this operation in the end is very cheap (copy then clear very few bytes, i.e. sizeof the structure).