Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I swap in a new value for a field in a mutable reference to a structure?

Tags:

rust

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.

like image 961
arcyqwerty Avatar asked Nov 24 '14 05:11

arcyqwerty


1 Answers

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()); }     
like image 86
Francis Gagné Avatar answered Oct 02 '22 02:10

Francis Gagné