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

后端 未结 2 1347

I have a struct with a field:

struct A {
    field: SomeType,
}

Given a &mut A, how can I move the value of field

相关标签:
2条回答
  • 2020-11-22 06:53

    If your type implements Default, you can use std::mem::take:

    #[derive(Default)]
    struct SomeType;
    
    fn foo(a: &mut A) {
        let mut my_local_var = std::mem::take(&mut a.field);
    }
    

    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 Option::take uses mem::take, just like the more generic answer above shows, but it is wrapped up nicely for you:

    pub fn take(&mut self) -> Option<T> {
        mem::take(self)
    }
    
    0 讨论(0)
  • 2020-11-22 06:56

    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());
    }    
    
    0 讨论(0)
提交回复
热议问题