Swap out an owned data member (e.g. Vec)?


#1

Hello all,

I’m puzzled by a very simple operation I’d like to do. I have a struct which owns a Vec. I want to consume that Vec, and replace it with an empty Vec. I could do this using its drain method, but then I’d get an Iterator, where I want an actual Vec. True, I could collect that Iterator to get myself a Vec again, but I doubt that would be an O(1) operation, in contrast to just copying the pointer, size and capacity information.

It seems like there must be an elegant solution to this problem, but I can’t think of it, or of how better to google for it. Any suggestions?


#2

using std::mem::swap or std::mem::replace should be enough. Replace with a Vec::new().

Note that these are elementary and important functions to know; they are not really low-level. They work on the ownership level.


#3

Thanks! Somehow, I never read the std::mem docs before. I guess its name made me think of low-level (and probably unsafe) details that I wouldn’t want to use. std::mem::replace is exactly the function I was imagining should exist! :slight_smile:


#4

In a way that’s true, most of std::mem is low level interfaces. However, three non-low level functions: std::mem::swap, std::mem::replace and std::mem::drop (that one is imported by prelude as drop) are really useful, and it’s worth checking those.