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?
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. I'm not worried about concurrency in this case.
If your field happens to be an
Option
, there's a specific method you can use —Option::take
:The implementation of
take
usesmem::replace
, just like the more generic answer shows, but it is wrapped up nicely for you:Use
std::mem::swap()
.Or
std::mem::replace()
.