Fix a method that moves a field out of &mut self
drain_all should hand every queued message to the caller and leave the inbox empty but usable. It does not compile: error[E0507]: cannot move out of `self.items` which is behind a mutable reference.
Constraints:
- Keep the signature
fn drain_all(&mut self) -> Vec<String>. - No
unsafeand no copy of the messages.
struct Inbox {
items: Vec<String>,
}
impl Inbox {
fn drain_all(&mut self) -> Vec<String> {
let v = self.items;
v
}
}
fn main() {
let mut inbox = Inbox { items: vec![String::from("a"), String::from("b")] };
let taken = inbox.drain_all();
println!("{taken:?} {}", inbox.items.len());
}Find and fix the bug.
Through &mut self the method may change items but not take it, or the struct would hold a moved-out field. mem::take(&mut self.items) returns the vector and leaves an empty one; mem::replace leaves a value you pick; mem::swap swaps two.
- Cloning the whole vector to satisfy the compiler: it copies every string when
mem::takejust puts an emptyVecin place - Reaching for
unsafeto move a field out:mem::takeandmem::replaceare safe and leave the field valid - Expecting
mem::taketo work for any type: it needsDefault; otherwise usemem::replacewith an explicit value
- How does
Option::takesolve the same problem for anOption<T>field? - When is changing the method to take
selfby value the better fix?
&mut self is a mutable reference: the method may change the fields, but the caller owns the struct. If let v = self.items; were allowed, inbox would be left with a field that holds no value, and at the end of main the vector would be dropped a second time. So the compiler refuses to move a field out from behind a reference.
A value can be taken out if another one is put in its place at once. std::mem::take returns the old value and leaves Default::default() — for a Vec that is an empty vector with no allocation:
use std::mem;
struct Inbox {
items: Vec<String>,
}
impl Inbox {
fn drain_all(&mut self) -> Vec<String> {
mem::take(&mut self.items)
}
}
fn main() {
let mut inbox = Inbox { items: vec![String::from("a"), String::from("b")] };
let taken = inbox.drain_all();
println!("{taken:?} {}", inbox.items.len());
}The program prints ["a", "b"] 0: the messages went to the caller, and the inbox is empty and ready for use.
Which function when:
mem::take(&mut x)— the type implementsDefault, and the default value works as "empty".mem::replace(&mut x, new)— the type has noDefault, or a specific value must take its place:mem::replace(&mut self.state, State::Idle).mem::swap(&mut a, &mut b)— two values must trade places, and neither may be left empty.
self.items.clone() compiles too, but it copies every string and leaves the messages in the inbox, which breaks the task's requirement.