Replace mutable reference with a value

Hi, I'm having a little trouble with a library I am working with.
The library has a struct that looks like this:

struct Foo;

impl Foo {
    fn bar(mut self) -> Self {
        // Does some stuff
    }
}

I am using Foo in a HashMap and am trying to do the following:

let ref: &mut Foo = hash_map.get_mut(&key).unwrap();
ref = ref.bar();

This doesn't work as bar takes ownership of the Foo instance. I have also tried doing std::mem::replace(ref, ref.bar()), but this doesn't work as I "cannot move out of ref because it is borrowed".

Is replacing ref with ref.bar() possible?

The problem is if the function panic the stack unwinding will touches invalid value. You can use take_mut crate which aborts the process unrecoverably in such case.

1 Like

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.