Is this a borrow checker limitation, or am I doing something wrong?

Is the borrow checker error in the following code due to a current limitation of the borrow checker, or am I doing something wrong? I would expect the borrow checker to be able to determine which code regions are reachable/mutually exclusive and which are not within the function's scope.

struct T {}

struct Test {
    i: i32,
    t: T,
}

impl Test {
    fn test<'a>(&'a mut self) -> Option<&'a T> {
        for _i in 0..10 {
            if let Some(outcome) = self.get() {
                return Some(&outcome);
            }
            else {
                self.i += 1;
            }
        }
        None
    }
    
    fn get(&mut self) -> Option<&T> {
        if self.i > 0 {
            Some(&self.t)
        } else {
            None
        }
    }
}


fn main() {
    let mut t = Test{i: -5, t: T{}};
    t.test();
}

Rust playground link.

I believe this is a polonius problem case. It looks extremely similar to the example in the polonius crate documentation.

fn get_or_insert (
    map: &'_ mut HashMap<u32, String>,
) -> &'_ String
{
    if let Some(v) = map.get(&22) {
        return v;
    }
    map.insert(22, String::from("hi"));
    &map[&22]
}
3 Likes