Scope of mutable borrow in a block

Hi Guys,

in a block, I'm calling a function returning a mutable reference. My understanding was that the reference is only valid within the block (thus is "disposed" as after the block closes).
However, when I'm trying to borrow again after the block closes, rust complaints with our beloved cannot borrow *self as mutable more than once at a time. This seems to be related to returning the value (when commenting out the return line, rust happily accepts this).

Can someone please shed some light into what is happening here?

Thanks!

struct Test {
    item: String
}

impl Test {
    fn foo<'a>(&'a mut self) -> &'a str {
        {
            let x = self.bar();
            if x.is_ascii() {
                return x
            }
        }
        self.bar() // error
    }

    fn bar<'a>(&'a mut self) -> &'a str {
        &self.item
    }
}

Your understanding it's correct, this is a limitation of the current borrow checker which "extends" the borrow of x until the end of the function due to it being returned. This should hopefully be fixed when Polonius, a new WIP borrow checker, will be implemented (though there's no ETA for now).

1 Like

The limitation is due to the conditional return. When possible, a workaround is to recreate any necessary borrows in a context where the return is unconditional.

It's not a problem with lexical scopes (blocks) really. If the reference was only valid inside the created scope, you couldn't return it from the function.

1 Like

Thanks @SkiFire13 and @quinedot for clarifying. Much appreciated.

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.