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.
Use 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().
fn foo(a: &mut A) { let mut my_local_var = mem::replace(&mut a.field, SomeType::new()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With