Branching borrow checker issue

⚓ Rust    📅 2026-05-26    👤 surdeus    👁️ 1      

surdeus

Can someone explain why this fails?

struct Test {
    inner: Vec<u8>,
}

impl Test {
    fn fails_but_why(&mut self) -> &mut u8 {
        // a fairly expensive/recursive call here
        if let Some(last) = self.inner.last_mut() {
            return last;
        }
        // only the plain reference is required at this point
        let as_ref = self.inner.as_slice();
        todo!("do something with `&[u8]`")
    }
    // is NOT something I'm willing to settle on
    fn works(&mut self) -> &mut u8 {
        let is_some = self.inner.last_mut().is_some();
        match is_some {
            true => self.inner.last_mut().unwrap(),
            false => {
                let as_ref = self.inner.as_slice();
                todo!("do something with `&[u8]`")
            }
        }
    }

}

I'm assuming it is yet another edge case, not handled properly by the current implementation of the compiler? Is there any well-known workaround, that would not require turning the first mutable borrow into a boolean true/false check, simply to "detach" the lifetime from the first call, before branching into either the former if let or the following as_ref?

3 posts - 3 participants

Read full topic

🏷️ Rust_feed