The line
let bar = &mut foo.a;
creates a reborrow of the a
field of foo
. As long as the reborrow is alive, the field can't be accessed via foo.a
anymore, but only via bar
. After the last use of bar
, you can use foo.a
again – once the reborrow is released, the original borrow is available again.
Reborrowing is very similar to borrowing itself. While a value is borrowed, you cannot access the original value until the borrow is released. The same happens when reborrowing. This makes sure that at any given time there is only a single active mutable borrow, and the borrowing rules are upheld.
The fact that you are dealing with a struct here is incidental. You can do the same with a mutable borrow to any value, e.g. after
let mut i = 17;
let borrow = &mut i;
let reborrow = &mut *borrow;
*reborrow += 4;
*borrow += 21;
the value of i
is 42. This code looks like there are multiple active mutable borrows to i
. However, at any given time only one of them can be used. The reborrow is released after it is last used, so the original borrow becomes usable again. If we swap the last two lines in this code, it won't compile anymore, since the reborrow would still be alive when borrow
is accessed, which is not allowed.
Unfortunately, the mechanics of reborrowing aren't currently documented in the Rust reference. A related, also not well documented topic are implicit reborrows that happen when a mutable reference is bound to a variable of a type that is already known to be a mutable reference.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…