HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfieldswapstructureforcanmutablevaluereferencenew

Problem

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.

Solution

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());
}

Code Snippets

fn foo(a: &mut A) {
    let mut my_local_var = SomeType::new();
    mem::swap(&mut a.field, &mut my_local_var);
}
fn foo(a: &mut A) {
    let mut my_local_var = mem::replace(&mut a.field, SomeType::new());
}

Context

Stack Overflow Q#27098694, score: 70

Revisions (0)

No revisions yet.