How to shorten the lifetime of a mut ref?

playground

struct A {
    b: Option<bool>,
    c: bool,
}

impl A {
    fn f(&mut self) -> Option<&mut bool> {
        if let Some(b) = self.b.as_mut() {
            Some(b)
        } else {
            self.g()
        }
    }

    fn g(&mut self) -> Option<&mut bool> {
        // maybe some complicated code
        Some(&mut self.c)
    }
}

I want to know how to make this code compiles without inlining method g, and in general, how to shorten the lifetime of a mut ref (in this case, the lifetime of self.b.as_mut()).

Looks like a polonius-type issue to me. I'm on mobile so I can't easily confirm it right now. If thats the case, then I like the writeup on the topic in this crate documentation which is worth a read :wink:

Annoying but straightforward workarounds include the approach of replacing the Some(b) return value by another call to self.b.as_mut().

1 Like

Thanks for the references you provided!

One workaround is to borrow again in the if block, so it doesn't apply to the else:

fn f(&mut self) -> Option<&mut bool> {
    if self.b.is_some() {
        self.b.as_mut()
    } else {
        self.g()
    }
}

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.