More than one mut borrow question

Hi, I would like to understand why in the following example we have an error of foo_two but not foo_one. I think those functions are equivalent. What I mean is that the inner call to ".val()" has to come before the outer one during compilation, right?.

pub struct MyStruct {
    pub val: usize,
}

impl MyStruct {

    pub fn val(&mut self, val: usize) -> usize {
        self.val + val
    }

}

pub fn foo_one(bar: &mut MyStruct) {
    let x = bar.val(0);
    bar.val(x);
}

pub fn foo_two(bar: &mut MyStruct) {
    bar.val(bar.val(0)); // <- ERROR: two mut borrows
}

It's because of how code is parsed from left to right. You can learn more from this thread that touched the exact same subject a few days ago: Why does this borrow last for whole statement?

3 Likes

Thx, Two-phase borrows is what I was looking for.