Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Transfer ownership to caller and re-instantiate field

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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());
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading