How do I move out of a struct field that is an Option?

Essentially, you can’t assign the value to self.attrib if it’s still owned by self.next_atrrib. That means you need to remove the value from self.next_attrib and then give ownership to self.attrib.

One way to do this would be to manually replace the value. For instance, you could use std::mem::replace to replace the value with None and take ownership of the current value as next_attrib. Then you can take the value and, if it is Some(_), you can place its content in self.attrib.:

impl SomeStruct {
    pub fn apply_changes(&mut self) {
        let next_attrib = std::mem::replace(&mut self.next_attrib, None);
        if let Some(se) = next_attrib {
            self.attrib = se;
        }
    }
}

Since this is a relatively common pattern, however, there is a utility function on Option to handle situations where you’d like to take ownership of the contents of an Option and set the Option to None. The Option::take method is what you want.

impl SomeStruct {
    pub fn apply_changes(&mut self) {
        if let Some(se) = self.next_attrib.take() {
            self.attrib = se;
        }
    }
}

See also:

Leave a Comment