The rule
There shall only be one usable mutable reference to a particular value at any point in time.
This is NOT a spatial exclusion (there CAN be multiple references to the same piece) but a temporal exclusion.
The mechanism
In order to enforce this, &mut T
is NOT Copy
; therefore calling:
test(mutable_reference);
should move the reference into test
.
Actually doing this would make it unusable later on and not be very ergonomic, so the Rust compiler inserts an automatic reborrowing, much like you did yourself:
test(&mut *mutable_reference);
You can force the move if you wanted to:
test({ let x = mutable_reference; x });
The effect
Re-borrowing is, in essence, just borrowing:
mutable_reference
is borrowed for as long as the unnamed temporary mutable reference exists (or anything that borrows from it),
- the unnamed temporary mutable reference is moved into
test
,
- at the of expression, the unnamed temporary mutable reference is destroyed, and therefore the borrow of
mutable_reference
ends.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…