Help understanding mutable references

I am a Rust newbie. While trying to understand ownership/borrowing concepts I've come across the following code snippet in a blog post.

And this compiles without an error. From what I've understood, you cannot have two mutable references to the same variable. In this case ref_i is a mutable reference to i, and so is the 'test' function's parameter 'i'. Clearly I am missing something.
Thank you in advance.

This is an example of reborrowing. Explicitly, it will be written as this:

fn test(i: &mut i32) {}
fn main() {
    let mut i: i32 = 1;
    let ref_i = &mut i;
    test(&mut *ref_i);
    *ref_i = 2;
}

In this case, ref_i is not passed into the test, but rather locked to get another mutable reference, "stacked" on top of it. Since test doesn't use the input reference in the output, it is unlocked just after the call and is usable again.

Now, in your example, there's no explicit borrowing, but Rust can add it implicitly - to allow one mutable reference be used several times consequently, it is reborrowed, and not moved, for each usage.

2 Likes

Thanks for the explanation! Are the reborrowing rules documented anywhere?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.