struct Foo {
pub v: Vec<Bar>
}
impl Foo {
pub fn magic(&mut self) {
let ans = Vec<Bar>::new();
// can we set ans = self.v
// and clear self.v ?
}
}
See above: I want to grab the vec and set the member field to empty (and process the vec later in the function). Is this "swap" possible to do on a &mut self ?
No, this will just clear the vec, you wont get its contents.
Also becaise Vec is lazily allocated, the only cost is the 24 bytes on the stack for the Vec when using replace.
It is generally O(n) but it's possible for the compiler to optimize a drain(..).collect::<Vec<_>>() into an O(1) operation (I don't know if it works now). Also there are cases where you would need to iterate over the drained values either way, and drain would be OK in these cases.