Sub topic 11
Reborrowing a Mutable Reference
This chapter assumes you know how to write functions that take &T and &mut T. It also assumes you know the rule that a value has either many shared borrows or one mutable borrow at a time, and that you understand non-lexical lifetimes (NLL), which end a borrow at its last use.
A &mut T can be passed to a function and then used again afterwards. That seems to conflict with Rust's move rules, because &mut T does not implement Copy. The mechanism that resolves it is called reborrowing.
The puzzle: `&mut` is not `Copy`
A shared reference &T is Copy. You can hand out as many copies as you like. A mutable reference must be unique, so it cannot be copied. Passing a non-Copy value to a function normally moves it, and the original variable can no longer be used.
The following program passes a &mut twice anyway:
fn push_one(v: &mut Vec<i32>) {
v.push(1);
}
fn main() {
let mut v = Vec::new();
let r = &mut v;
push_one(r);
push_one(r);
println!("{:?}", r);
}It compiles and prints [1, 1]. The compiler did not move r into the first call. It created a new, shorter-lived mutable reference to the same data and passed that instead.
What a reborrow is
A reborrow dereferences a reference and borrows the result again. Written out in full, the first call above is:
fn push_one(v: &mut Vec<i32>) {
v.push(1);
}
fn main() {
let mut v = Vec::new();
let r = &mut v;
push_one(&mut *r);
push_one(&mut *r);
println!("{:?}", r);
}Read &mut *r from the inside out. *r names the Vec that r points to. &mut borrows that place mutably, for a shorter period than r itself lives.
The reborrow has two properties:
- It borrows from
r, not fromvdirectly. While the reborrow is alive,ris treated as if it were mutably borrowed. You cannot useruntil the reborrow's last use. - It ends independently. When the reborrow's last use passes,
rbecomes usable again. In the example, eachpush_onecall ends its reborrow when the call returns.
Where the compiler reborrows for you
The compiler inserts a reborrow automatically in two common situations.
Method calls. r.push(2) is shorthand for Vec::push(&mut *r, 2). The method receiver is reborrowed, so calling methods through r repeatedly never consumes it.
Coercion sites with a known reference type. A function argument is a coercion site. When the parameter type is written as &mut T, the compiler knows a &mut is expected and reborrows. The same applies to a let with an explicit type annotation.
Reborrowing does not happen when the target type is not known to be a &mut. This table shows the difference:
| Code | What happens to `r` |
|---|---|
| `let a = r;` | Moves `r`. No expected type forces a reborrow. |
| `let a: &mut Vec<i32> = r;` | Reborrows. The annotation names a reference type. |
| `push_one(r)` with parameter `&mut Vec<i32>` | Reborrows. |
| `consume(r)` with parameter `T` (generic) | Moves `r`. |
| `consume(&mut *r)` with parameter `T` | Reborrows explicitly. |
When inference fails: generic parameters
The generic case is the one that surprises people. The parameter type T could be anything, so the compiler does not assume a reference is intended. It moves the value:
fn consume<T>(_value: T) {}
fn main() {
let mut v = vec![1];
let r = &mut v;
consume(r);
r.push(2);
}This does not compile. The error is E0382, "borrow of moved value: r". The call consume(r) moved the &mut Vec<i32> into the function.
Write the reborrow yourself to fix it:
fn consume<T>(_value: T) {}
fn main() {
let mut v = vec![1];
let r = &mut v;
consume(&mut *r);
r.push(2);
println!("{:?}", r);
}This pattern shows up when you pass a &mut to a function bounded by a trait, such as impl Write or impl Iterator. For Write, &mut W implements the trait when W does, so the explicit reborrow is the usual fix.
Using the original while a reborrow is live
The reborrow is a real borrow, so the aliasing rules apply to it. This program is accepted because the inner reborrow is last used before r is touched again:
fn main() {
let mut s = String::from("a");
let r = &mut s;
let inner = &mut *r;
inner.push('b');
r.push('c');
println!("{r}");
}Swap the order of the last two uses and it breaks:
fn main() {
let mut s = String::from("a");
let r = &mut s;
let inner = &mut *r;
r.push('c');
inner.push('b');
println!("{r}");
}The compiler rejects this with E0499, "cannot borrow *r as mutable more than once at a time". inner is still needed on the line after r.push('c'), so r is still suspended. NLL decides the boundary by the reborrow's last use, not by the end of the block.
Shared reborrows from a `&mut`
You can reborrow a mutable reference as shared with &*r. While any such shared reborrow is live, writes through r are blocked. This is the vector example from the borrowing-rules chapter, with r as the owner of the access:
fn main() {
let mut v = vec![1, 2, 3];
let r = &mut v;
let first = &r[0];
r.push(4);
println!("{first}");
}This fails with E0502, "cannot borrow *r as mutable because it is also borrowed as immutable". Indexing r[0] implicitly reborrows *r as shared, and first keeps that shared reborrow alive. Move the println! above r.push(4) and the program compiles.
The conversion only goes one way. You can reborrow &mut T as &T. You cannot get a &mut T from a &T.
Returning a reborrow from a function
A function that takes &mut and returns a reference into the data returns a reborrow. Lifetime elision ties the output lifetime to the input, so the caller's access is suspended for as long as the result lives:
fn first_mut(v: &mut Vec<i32>) -> &mut i32 {
&mut v[0]
}
fn main() {
let mut v = vec![10, 20];
let slot = first_mut(&mut v);
*slot += 1;
v.push(30);
println!("{:?}", v);
}This compiles because slot is last used before v.push(30). Move *slot += 1; below the push and you get E0499, because the borrow that slot carries would still be live.
Reborrowing versus moving out
A reborrow is the only way to lend a &mut and keep it. If you really want to give it away, write let a = r; and accept that r is gone. Some APIs need this. A function that stores a &mut in a returned struct might consume the argument, and the caller's reference then stays suspended for as long as that struct lives.
You also cannot move data out of a reference. let owned = *r; fails for non-Copy types such as Vec, with E0507, "cannot move out of *r which is behind a mutable reference". Use std::mem::take(r) or std::mem::replace(r, new) to swap in a replacement value while taking the old one. Borrow with &mut *r, or clone.
Common mistakes
- Expecting a generic call to reborrow. Add
&mut *rwhen the parameter isTorimpl Trait. - Holding a reborrow in a variable too long. Keep the reborrow's last use before the next use of
r, or drop the variable by letting it fall out of use. - Reading the error as being about
v. Messages that mention*rpoint to a reborrow. The fix is usually to shorten that reborrow, not to changev.
Exercise
In fn push_one(v: &mut Vec<i32>), calling push_one(r) twice with the same r: &mut Vec<i32> compiles. Why does consume(r) with fn consume<T>(_t: T) followed by r.push(2) not compile, and how do you fix it?
Show answer
With a parameter of type &mut Vec<i32>, the compiler knows a mutable reference is expected and inserts the reborrow &mut *r, so r stays usable. With a generic T, no reference type is known, so r is moved into the call. The later r.push(2) then uses a moved value (E0382). The fix is to write the reborrow explicitly: consume(&mut *r).
Exercise
Given let r = &mut s; let inner = &mut *r;, name one line you can write between these and the last use of inner that fails to compile, and say which error code you expect.
Show answer
Any use of r while inner is still needed later, for example r.push('c'); followed by inner.push('b');. The compiler reports E0499, because *r would be borrowed mutably twice at once.