How can I swap in a new value for a field in a mut

2019-01-03 00:03发布

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.

标签: rust
2条回答
Animai°情兽
2楼-- · 2019-01-03 00:40

If your field happens to be an Option, there's a specific method you can use — 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 take uses mem::replace, just like the more generic answer shows, but it is wrapped up nicely for you:

pub fn take(&mut self) -> Option<T> {
    mem::replace(self, None)
}
查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-03 00:44

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());
}    
查看更多
登录 后发表回答