Cannot move a field of a struct

  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.

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

Worked; thanks!