英文:
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<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?
答案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(&mut self) -> Record {
return replace(&mut self.record, Record::new());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论