&mut self, swapping vec

  1. I have
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 ?
  }
}
  1. 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 ?

You can use std::mem::replace for this.

let ans = std::mem::replace(&mut self.v, Vec::new());
2 Likes

You can also use drain(..) to take all items out of a Vec.

1 Like

O(1) was not an original requirement. However, is it correct that:

@Riateche 's drain is O(n) as it involves iterating through the elements, while @RustyYato 's replace is O(1) ?

Yes

Shouldn't be a need to swap.

let ans = &mut self.v;
ans.clear();

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.

1 Like

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.