
Recall first from Partial moves, signatures, and the Copy Drop conflict
- After a partial move, intact fields remain usable, but operations requiring the complete struct must wait until the missing field is restored.
- Passing a non-Copy value by value transfers ownership. Passing a reference leaves ownership with the caller.
- Explicit drop consumes its argument. Passing a Copy value leaves the original usable.
Shared references allow several readers
3 min readThe ownership lessons ended with the Copy and Drop conflict. This lesson answers how to use a value without moving or copying it: by borrowing.
Consider a Linux program that receives bytes in a buffer and then sends those bytes to a log. With read(2), the buffer receives bytes from a file descriptor. With write(2), the buffer supplies bytes to a file descriptor. Both calls can report a short transfer, so real code uses the returned byte count. The access distinction comes before counting bytes. Receiving data requires permission to change the buffer, while supplying existing data requires permission to read it. The read(2) and write(2) manual pages describe those two buffer roles.
In Rust, that distinction can appear in the type of a reference. A a reference of type &T that permits shared access to a value of type T lets code inspect an ordinary value. Through &u32, for example, code can read the integer and use the reading in a calculation. It cannot assign a different integer through that reference. The rule applies even when the original binding was declared with let mut. That declaration permits mutation of the owned value when access is available. The type of the reference determines what code can do through the reference itself.
This example uses a count of pending samples. Two references read the same count. The code uses each reference after the other has already been used once, so the two shared borrows overlap.
fn main() {
let pending = 6_u32;
let status: &u32 = &pending;
let diagnostics: &u32 = &pending;
assert_eq!(*status, 6);
assert_eq!(*diagnostics, 6);
assert_eq!(*status, *diagnostics);
}
Here &pending borrows pending, and *status accesses the integer that status refers to. In the assertions, the code reads the integer. The two reference bindings refer to one owned value, and creating them leaves ownership with pending. The final assertion reads both references in the same statement, which is allowed because each borrow grants shared access. The result would be the same with a single reference used twice, but the two names make it possible to see which borrow each use requires.
Each read sees the value at the same location. A shared reference does not create a stored snapshot of that value. In this example, Rust prevents the u32 from being changed while those shared borrows are still needed. Inspection code can therefore read *status, perform another read through diagnostics, and read *status again with both references still valid. The reasoning is about access to pending. A write to a separate, unborrowed counter can occur during those reads.
Notice the difference between what the code actually does and what its type permits. status happens to be used only in assertions, but it would still have shared access if the code used it to calculate a threshold or decide whether to print a message. Conversely, even a single shared reference cannot update the integer. Shared access describes permission, and the number of readers is a consequence of those permissions being compatible.
Mutable references require exclusive access
4 min readA a reference of type &mut T that permits exclusive access to a value of type T lets code both read and write the value. For the sample count, *update += 1 reads the old count and stores the incremented count through the same reference. The word mutable describes a permission. Code can use a mutable reference just to read, but the borrow still requires exclusive access while it is active.
fn main() {
let mut pending = 6_u32;
{
let update: &mut u32 = &mut pending;
assert_eq!(*update, 6);
*update += 1;
assert_eq!(*update, 7);
}
assert_eq!(pending, 7);
}
The binding pending is declared with let mut so the code can borrow it mutably. The binding update needs no mut because the code writes to the referenced integer and never reassigns update itself. When the program inspects pending after the inner block, it sees the updated count. The mutable borrow gave permission to modify the original value, and the owner can access that value directly again after the borrow ends.
The rule for independent borrows of the same value is one writer or many readers. While the mutable borrow is active, no other independent reference to that value can be active. That excludes a second &mut and also excludes an &T. Direct access through the owner is restricted too. If the example read pending directly before the last assertion through update, that direct read would conflict with the exclusive borrow. The exact spelling of the read makes no difference to the exclusivity requirement.
Now consider code that starts an inspection, updates the count, and then tries to finish the original inspection.
fn main() {
let mut pending = 6_u32;
let status = &pending;
assert_eq!(*status, 6);
let update = &mut pending;
*update += 1;
assert_eq!(*status, 6);
}
Rust rejects this program. The final assertion still needs the shared borrow of pending, so the attempt to borrow pending mutably comes while the shared borrow is active. Changing the expected value in the last assertion to 7 would leave the borrow conflict in place. The compiler checks whether the access is permitted before the program can run and compare any values. rustc 1.100.1 reports it like this (shown with the path cargo prints):
error[E0502]: cannot borrow `pending` as mutable because it is also borrowed as immutable
--> src/main.rs:6:18
|
3 | let status = &pending;
| -------- immutable borrow occurs here
...
6 | let update = &mut pending;
| ^^^^^^^^^^^^ mutable borrow occurs here
...
9 | assert_eq!(*status, 6);
| ---------------------- immutable borrow later used here
The same reasoning applies with the order of reference creation reversed. Suppose update first borrows pending mutably, status then borrows pending directly for reading, and a later line writes through update. The later write still needs the exclusive borrow when status is created. Similarly, if two mutable references independently borrow pending and both are used after the second is created, the first still needs exclusive access at the point where the second requests it. Both programs are rejected.
These examples use a single function on one thread. The the compiler analysis that enforces Rust’s borrowing rules checks the requested accesses during compilation. It needs no device and observes no running program. You can use cargo check in the project directory to see whether the compiler accepts a borrow. Use cargo run when you also want the assertions to execute.
A borrow can end at its last use
4 min readThe references in the previous examples were declared with let, and their bindings have names that stay in scope until the end of the enclosing block. The borrow checker can determine that a borrow is no longer needed before that point. Rust calls this borrow checking that can determine where a borrow is needed from how the reference is used, beyond simply looking at the enclosing block. In straight-line examples like these, look for the last use of a reference. The borrow can end there, so a later statement in the same block can request an incompatible kind of access.
fn main() {
let mut pending = 6_u32;
let status = &pending;
assert_eq!(*status, 6);
let update = &mut pending;
*update += 1;
assert_eq!(*update, 7);
let latest = &pending;
assert_eq!(*latest, 7);
}
The first assertion is the last use of status. When update requests exclusive access, the shared borrow through status is finished. The assignment is the first use of update and the next assertion is its last. By the time latest requests shared access, the mutable borrow has ended. The three reference bindings are all declared in the same block. Rust accepts the code because the required shared, exclusive, and shared accesses occur in that order without conflicting overlaps.
A small edit can change that conclusion. Add assert_eq!(*status, 6); at the bottom of main. Now the reference from the first inspection is needed through the new final assertion. Its shared borrow extends across the statement creating update. The compiler rejects the program for the same reason as in the earlier conflicting example. Borrow checking considers later uses when deciding whether a borrow is still needed at an earlier statement.
The last write and the last use can also be different statements. In the working example, *update += 1 is the last write through update, but assert_eq!(*update, 7) still uses that reference. Moving let latest = &pending; to just before that assertion creates a conflict if the final assertion through latest stays where it is. The mutable borrow still requires exclusivity during the read through update. When checking the order by hand, mark every use of each reference, including assertions that only read.
If the program needs to compare a count before and after the update, it can record the old numeric reading with let before = *status; before borrowing mutably. Since the count is a u32, this gives before its own integer value. Using before after the update does not use status again. If the program only needs to inspect the new count, it can read through update or create a fresh shared reference after the final use of update, as the working example does. Those choices also keep the intent of each read clear. before is a saved observation, while latest reads the current count.
When you review code that reads and updates one value, identify the value each reference borrows, mark the borrows as shared or mutable, and follow each one through its final use. Shared borrows can overlap. An exclusive borrow must have the value to itself. The practice below lets you check how moving a single read affects that ordering.
The next lesson, Creating references and slices, shows how to create references to values and how to borrow a range of elements as a slice. The same access rules will tell you when code can inspect or change the borrowed elements.
Key takeaways
- Several shared references can read the same ordinary value at the same time.
- A mutable reference permits reading and writing and requires exclusive access to the borrowed value.
- Rust checks borrow conflicts at compile time.
- In straight-line code, a borrow can end at its last use even while the reference binding is still in scope.
Reflect
- Explain to a colleague, in two sentences: identify the access permitted by &T and &mut T.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Rust docsThe Rust Book: References and borrowing
- Man pageread(2): read from a file descriptor
- Man pagewrite(2): write to a file descriptor
Official documentation first. Links checked when the lesson was published.