Cannot move a field of a struct


#1
  1. I have the following code:
pub struct Foo {}

impl Foo {
    pub fn new() -> Foo { panic!(); }
}


pub struct Bar {
    foo: Foo,
}



impl Bar {
    pub fn swap(&mut self) -> Foo {
        let ans = self.foo;
        self.foo = Foo::new();
        ans
    }
}

I understand why we can not move “self.foo” – but is there a wa to amke this work? I want to construct a new Foo::new(), then swap the self.foo field, and return the old value.


#2
pub fn swap(&mut self) -> Foo {
        std::mem::replace(&mut self.foo, Foo::new())
}

#3

Worked; thanks!