[英]How can I swap in a new value for a field in a mutable reference to a structure?
I have a struct with a field:我有一个带有字段的结构:
struct A {
field: SomeType,
}
Given a &mut A
, how can I move the value of field
and swap in a new value?给定一个&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.
}
The end goal would be the equivalent of a get_and_set()
operation.最终目标相当于get_and_set()
操作。 I'm not worried about concurrency in this case.在这种情况下,我并不担心并发性。
Use std::mem::swap()
.使用std::mem::swap()
。
fn foo(a: &mut A) {
let mut my_local_var = SomeType::new();
mem::swap(&mut a.field, &mut my_local_var);
}
Or std::mem::replace()
.或std::mem::replace()
。
fn foo(a: &mut A) {
let mut my_local_var = mem::replace(&mut a.field, SomeType::new());
}
If your type implements Default
, you can use std::mem::take
:如果您的类型实现Default
,则可以使用std::mem::take
:
#[derive(Default)]
struct SomeType;
fn foo(a: &mut A) {
let mut my_local_var = std::mem::take(&mut a.field);
}
If your field happens to be an Option
, there's a specific method you can use — Option::take
:如果您的字段恰好是Option
,则可以使用特定的方法 — Option::take
:
struct A {
field: Option<SomeType>,
}
fn foo(a: &mut A) {
let old = a.field.take();
// a.field is now None, old is whatever a.field used to be
}
The implementation of Option::take
uses mem::take
, just like the more generic answer above shows, but it is wrapped up nicely for you: Option::take
的实现使用mem::take
,就像上面显示的更通用的答案一样,但它为您很好地包装起来:
pub fn take(&mut self) -> Option<T> {
mem::take(self)
}
See also:也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.