我知道很棒的 Rust 特性:
Foo {
fieldX: someValue,
..Self::default()
}
我想在 &mut self
的方法中使用它, 不接触字段 f10
和 f11
并将其他设置为默认值:
#[derive(Default)]
struct Foo {
f1: u32,
//...
f10: Vec<u32>,
f11: Vec<u32>,
}
impl Foo {
fn f1(&mut self) {
let new_me = Foo {
f10: self.f10,
..Self::default()
};
*self = new_me;
}
}
但是编译器说:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:12:18
|
12 | f10: self.f10,
| ^^^^ cannot move out of borrowed content
我怎样才能:
- 留下
f1
的签名原样:&mut self
- 不复制任何
Vec<>
, 只会动 不写无聊的代码,喜欢
self.f1 = 0; self.f2 = 0; self.f3 = None; // ...
最佳答案
我会将整个 self
替换为默认值,然后保留先前值中有趣的字段:
use std::mem;
impl Foo {
fn f1(&mut self) {
let old = mem::replace(self, Self::default());
self.f10 = old.f10;
}
}
关于rust - 如何更新结构,将大部分但不是所有字段设置为默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42699222/