将所有权转移到调用者并重新实例化字段。

huangapple go评论72阅读模式
英文:

Transfer ownership to caller and re-instantiate field

问题

pub struct Record {
    pub raw_content: String,
    pub fields: HashMap<String, String>,
}

impl Record {
    pub fn reset(&mut self) -> Record {
        let raw_content = self.raw_content.clone();
        let fields = self.fields.clone();
        let old_record = Record { raw_content, fields };
        
        self.raw_content.clear();
        self.fields.clear();

        old_record
    }
}
英文:

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&lt;String, String&gt;,
}
fn pub reset(&amp;mut self) -&gt; 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
  --&gt; 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 = &amp;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?

答案1

得分: 3

你可以使用std::mem::replace来实现这个功能。

use std::mem::replace;

pub fn reset(&mut self) -> Record {
  return replace(&mut self.record, Record::new());
}

英文:

You can do this with std::mem::replace.

use std::mem::replace;

pub fn reset(&amp;mut self) -&gt; Record {
  return replace(&amp;mut self.record, Record::new());
}

huangapple
  • 本文由 发表于 2023年7月11日 08:05:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76657990.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定