What is the right way to move an object?

Hi everyone, I tried to find an answer to my very easy question but couldn't find any.

I want to move an object that cannot be copied, out of other object, to be used in some other place. This is my code:

pub struct SomeResource { ... }

pub struct AllResources {
    some: Option<SomeResource>
}

impl AllResources {
    pub fn move_resource(&mut self) -> Option<SomeResource> {
        // mem::replace(&mut self.some, None)
        let some = self.some;
        self.some = None;
        some
    }
}

This code example produces this compilation error:

cannot move out of self.some which is behind a mutable reference [E0507]

And everything compiles and works if I use the commented line instead. I don't see any problem in using the commented line, my question is - what is the right way to do this thing?

I saw some post here claiming that borrowing checker can recognize this pattern, but it doesn't recognize.

The right way is to use mem::replace or another method like it.

The other pattern can work for things you have ownership of, but it doesn't work if you just have a mutable reference. When it's behind a reference, it must be valid at all times, and you can't temporarily make it invalid.

2 Likes

For an Option specifically, you can use Option::take, which would be self.some.take() in the above snippet

3 Likes

Perfect. This answers my question. Thank you @azriel91

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.