I want to implement a reset method (in an unrelated struct) that reinstantiates a field (Record struct), and transfer the ownership of previous value to the caller:
pub struct Record {
pub raw_content: String,
pub fields: HashMap<String, String>,
}
fn pub reset(&mut self) -> Record {
let record = self.record;
self.record = Record::new();
return record;
}
However, when I try to do this, the compiler gives the following error:
error[E0507]: cannot move out of `self.record` which is behind a mutable reference
--> src/parser.rs:45:22
|
45 | let record = self.record;
| ^^^^^^^^^^^ move occurs because `self.record` has type `Record`, which does not implement the `Copy` trait
|
help: consider borrowing here
|
45 | let record = &self.record;
| +
I don’t want to borrow the object; I want to give it up to the caller then re-initialize field. How do I accomplish this?
>Solution :
You can do this with std::mem::replace.
use std::mem::replace;
pub fn reset(&mut self) -> Record {
return replace(&mut self.record, Record::new());
}