我有一个带字段的结构:
struct A {
field: SomeType,
}
Run Code Online (Sandbox Code Playgroud)
给定a &mut A
,如何移动值field
并交换新值?
fn foo(a: &mut A) {
let mut my_local_var = a.field;
a.field = SomeType::new();
// ...
// do things with my_local_var
// some operations may modify the NEW field's value as well.
}
Run Code Online (Sandbox Code Playgroud)
最终目标相当于一项get_and_set()
行动.在这种情况下,我并不担心并发性.
我想收集结构的更改并立即应用它们.基本大纲如下所示:
enum SomeEnum {
Foo,
Bar,
}
struct SomeStruct {
attrib: SomeEnum,
next_attrib: Option<SomeEnum>,
}
impl SomeStruct {
pub fn apply_changes(&mut self) {
if let Some(se) = self.next_attrib {
self.attrib = se;
}
self.next_attrib = None;
}
}
Run Code Online (Sandbox Code Playgroud)
这会产生以下编译器错误:
Run Code Online (Sandbox Code Playgroud)error[E0507]: cannot move out of borrowed content --> src/lib.rs:13:27 | 13 | if let Some(se) = self.next_attrib { | -- ^^^^ cannot move out of borrowed content | | | hint: to prevent move, use `ref se` or `ref mut se` …