Chapter 5 of 16 · Part I, Foundations
Borrowing, and why the compiler counts your references
Why Rust allows many readers or one writer, the bug that rule prevents, how reborrowing and split borrows work, and how it compares with ref, out and in in C#.
This chapter assumes you can recognize a move. You will learn how a function can use a value without taking it, and how to repair conflicting borrows. Start with the reference rule; return to the optimization discussion after you can explain the compiler errors.
Moving ownership into every function you call would be unbearable, so Rust lets you lend a value instead. A borrow is a reference, written with an ampersand, and it does not take ownership.
fn length_of(s: &String) -> usize {
s.len()
}
fn main() {
let name = String::from("db-1");
let n = length_of(&name);
println!("{} is {} bytes", name, n); // name is still ours
}
The program prints db-1 is 4 bytes. Passing &name lends access to the string, so main can still print name afterward. Passing name to a function that accepts an owned String would move it instead. That is the distinction to notice before adding the borrowing rules.
What the rule actually says
There are two kinds.
&Tis a shared borrow. Multiple shared borrows may overlap; ordinary mutation through them is prohibited, with interior-mutability types providing controlled exceptions.&mut Tis an exclusive borrow. Safe code cannot use conflicting borrows of the same place while it is active. Shorter reborrows through it are allowed, as we'll see below.
The Rust Book states it as: at any given time you can have either one mutable reference or any number of immutable references, and references must always be valid (references and borrowing). Memorize that, then attach two footnotes to it, because each one costs a newcomer an afternoon.
The rule is about places, not names. self.left and self.right are two places. You can hold &mut self.left and &self.right simultaneously and the compiler is fine with it, because it tracks the path, not the variable at the root of the path. That gets important further down this chapter, and it is also where the checker's limits show.
"At any given time" is not "in the same block". A borrow's active region can end after its last relevant use rather than at the closing brace, although control flow, returned references, and destructors can affect the region. That was not always true, and the older model is still what most people carry in their heads, so I will come back to it.
One more thing, and it is the single most useful reframing I can offer. Rust calls &mut a mutable reference, so people read the rule as being about writing. It is not. It is about exclusivity. Mutation is what you are permitted to do because you have exclusivity, not the reason for the restriction. Read &mut T as an exclusive capability to access this place: while it is active, other conflicting accesses are restricted. That mental model is more useful than simply calling it writable, though reborrows and interior mutability require the finer rules.
Why aliasing plus mutation costs you speed
Safety is the argument everyone leads with. The optimization argument gets less airtime and is easier to demonstrate than to describe.
Here is a function in C#. Nothing clever in it.
static void Compute(ref int input, ref int output)
{
if (input > 10) output = 1;
if (input > 5) output *= 2;
}
Call it with two different variables and you get 2. Call it with the same variable twice and you get 1. Outputs below are from .NET 9.0.10:
int a = 12;
Compute(ref a, ref a);
Console.WriteLine(a); // prints 1
int inp = 12, outp = 0;
Compute(ref inp, ref outp);
Console.WriteLine(outp); // prints 2
Now stand where the JIT stands. It would like to load input once into a register and keep it there, because the second if reads it again and a register beats a memory load. It is not allowed to. The write to output might be a write to input, since both are addresses and nothing in the signature rules it out, so the language semantics require the second read to see the write. The first call proves that is not paranoia. The value genuinely changed between the two reads.
This is not a C# weakness. It is the default in every language with unrestricted references. C offers restrict so you can promise the compiler a pointer is unaliased, but it is opt-in, unchecked, and rare outside numeric kernels. Get it wrong and you have undefined behavior with no diagnostic. C++ never standardized it at all; the major compilers ship __restrict as an extension and most codebases never type it.
Rust gets the promise for free, because the types already made it. Write the same function with &u32 and &mut u32 and the aliased call does not exist:
fn compute(input: &u32, output: &mut u32) {
if *input > 10 {
*output = 1;
}
if *input > 5 {
*output *= 2;
}
}
fn main() {
let mut a: u32 = 12;
compute(&a, &mut a);
println!("{a}");
}
error[E0502]: cannot borrow `a` as mutable because it is also borrowed as immutable
--> src/main.rs:12:17
|
12 | compute(&a, &mut a);
| ------- -- ^^^^^^ mutable borrow occurs here
| | |
| | immutable borrow occurs here
| immutable borrow later used by call
For more information about this error, try `rustc --explain E0502`.
Read the bottom annotation, because it is doing the real work. The shared borrow of a is not merely created before the exclusive one. It is still needed at the moment of the call. That overlap is the violation. Every diagnostic in this chapter has a line like that, and it is the line that tells you which code to move.
Because the case cannot be written, rustc can tell the backend so. Depending on compiler version and optimization settings, rustc can communicate aliasing information to LLVM using attributes such as noalias, which is modeled on C's restrict: memory reached through pointers based on that argument is not reached through pointers not based on it, for any location that gets modified during the call (LLVM language reference). Once LLVM believes that, it can hold values in registers across intervening writes, delete redundant loads, drop writes nothing reads, reorder memory operations, and vectorize loops it would otherwise have to treat as opaque. The Rustonomicon's chapter on aliasing has the clearest short list, and it uses a version of the same compute function to make the point.
The bug this is really about
You have hit this in C#, and the compiler let you write it:
var servers = new List<string> { "db-1", "db-2" };
foreach (var s in servers)
{
if (s == "db-1") servers.Add("db-3");
}
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
The mechanism deserves precision, because it explains both what the check costs and what it misses. List<T> keeps an internal _version counter that every Add, Insert, Remove and Clear increments. The enumerator snapshots the counter when it is created and compares it at the top of every MoveNext, throwing when they differ (List.cs in dotnet/runtime). This version check is part of the enumerator's implementation. The machine-code cost depends on the JIT and surrounding loop; measure a hot path before assuming every check survives optimization. And because it fires at run time, it finds the bug only on the path that actually executed.
Arrays get no protection at all. Same runtime, same foreach, no counter:
var arr = new[] { 1, 2, 3 };
foreach (var x in arr)
{
if (x == 1) arr[2] = 99;
Console.Write($"{x} ");
}
// prints: 1 2 99
No exception. The loop reads the value you wrote mid-iteration. That is defensible behavior, and it is also exactly the surprise the version counter exists to prevent on List<T>, which tells you the protection is a per-type decision made by a library author, not a property of the language.
Rust's version of the list case never reaches run time.
fn main() {
let mut servers = vec!["db-1", "db-2"];
for s in &servers {
if *s == "db-1" {
servers.push("db-3");
}
}
}
error[E0502]: cannot borrow `servers` as mutable because it is also borrowed as immutable
--> src/main.rs:5:13
|
3 | for s in &servers {
| --------
| |
| immutable borrow occurs here
| immutable borrow later used here
4 | if *s == "db-1" {
5 | servers.push("db-3");
| ^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
For more information about this error, try `rustc --explain E0502`.
for s in &servers creates a shared borrow that the loop holds until it finishes. push takes &mut self. Those cannot overlap. The conflicting safe borrows are rejected at compile time, without relying on this particular runtime version check. You still need tests for the rest of the loop's behavior.
The fix is the one you would have written in C# anyway, minus the hope:
let mut to_add = Vec::new();
for s in &servers {
if *s == "db-1" {
to_add.push("db-3");
}
}
servers.extend(to_add);
Now sit with why this matters beyond tidiness. push may reallocate the vector's buffer and copy the elements to a new address, which would leave anything pointing into the old buffer aimed at freed memory. C# never gets there. List<T>.Enumerator holds the list and reads _items through it on every MoveNext, so a resize just means it follows the new array, and even if something did still hold the old one the collector would keep it alive. The worst outcome is a confusing exception. In a language with no collector, the identical code is a use-after-free. Rust does not have to pick between the exception and the crash. It deleted the third option by making the situation unexpressible.
Where you meet it first
The pattern that catches every newcomer is smaller than a loop:
fn main() {
let mut data = vec![1, 2, 3];
let first = &data[0];
data.push(4);
println!("{first}");
}
error[E0502]: cannot borrow `data` as mutable because it is also borrowed as immutable
--> src/main.rs:4:5
|
3 | let first = &data[0];
| ---- immutable borrow occurs here
4 | data.push(4);
| ^^^^^^^^^^^^ mutable borrow occurs here
5 | println!("{first}");
| ----- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
Move the println! above the push and it compiles. Nothing else changes.
That fix exposes the footnote I promised. I said a borrow is live from creation until its last use. The simpler model most people start with is that a borrow lives until the end of the enclosing block, and that simpler model used to be the truth. Before the 2018 edition, borrow regions were lexical. The reordered version above would still have failed, because first counted as borrowed all the way to the closing brace whether you touched it again or not.
What replaced it is called non-lexical lifetimes. The borrow checker now runs over the control flow graph of a function instead of its block structure, and a borrow's region is the set of program points where it might still be used. The RFC is readable if you want the reasoning.
The rollout took years, which is worth knowing if you read old code or old advice. NLL shipped with the 2018 edition in Rust 1.31. Code on the 2015 edition ran in a migration mode that executed both checkers and compared them, downgrading the new checker's complaints to warnings. That mode was narrowed release by release until Rust 1.63 in August 2022, when the old borrow checker was removed and all Rust code became NLL-checked. It is why Rust written before 2018 contains more artificial { } blocks than anybody enjoyed typing.
The practical habit that falls out: when the compiler rejects something, look for where the borrow is last used, not where it was created. Every diagnostic above carries an annotation saying the borrow is used later, either "later used here" pointing at a line, or "later used by call" when the use is the call you are standing in. That line is the constraint. The line with the carets is only the victim.
Methods borrow without asking
Something quietly confuses people for weeks here, and it is not in the rule at all.
let mut v = vec![1, 2, 3];
let n = v.len();
v.push(4);
You never wrote an ampersand. But len is fn len(&self) -> usize and push is fn push(&mut self, value: T), so the compiler inserted &v for the first call and &mut v for the second. That insertion is called autoref, and it happens during method resolution. Most method calls you write are therefore borrows you did not type, and which kind of borrow comes from a signature at the other end that you did not read. The exception is a receiver declared as plain self, which consumes the value instead, and that is exactly why into_iter and friends are named the way they are.
In C# you have no equivalent habit to draw on. Every instance method call on a class gets the same this, and the difference between a getter and a mutator is naming convention. Structs do a little better, since a readonly member is checked, but that check is about copies, not about who else holds the object. In Rust the difference is load bearing. conn.stats() and conn.reset_stats() lock different amounts of the program, and neither call site shows it.
Which sets up an oddity. By the strict rule, this should be illegal:
let mut v = vec![1, 2, 3];
v.push(v.len() as i32);
The &mut v for push is created before the arguments are evaluated, and v.len() needs a &v. Two overlapping borrows, one exclusive. It compiles anyway, and it compiles because of a special case called two-phase borrows. A compiler-inserted &mut starts life reserved, behaving like a shared borrow, and only activates into a real exclusive borrow at the point of the call. Between reservation and activation, other shared borrows are allowed.
The part worth remembering is the scope of the exemption. Two-phase borrows apply only to borrows the compiler inserted for you: the autoref on a method receiver, mutable reborrows in argument position, and overloaded compound assignment operators. Write the &mut yourself and you get the strict rule back. That asymmetry is why v.push(v.len() as i32) works and a hand-rolled equivalent sometimes does not, and knowing the reason saves you from concluding the checker is arbitrary.
Reborrowing, or why &mut works at all
&mut T does not implement Copy. Moving it is a real move. So this should fail:
fn takes(v: &mut Vec<i32>) { v.push(0); }
fn main() {
let mut v = vec![1, 2, 3];
let r = &mut v;
takes(r);
takes(r); // r was moved into the first call, surely
println!("{r:?}");
}
It compiles and prints [1, 2, 3, 0, 0]. What happens is a reborrow. When you pass a &mut T where a &mut T is expected, the compiler does not move your reference. It rewrites the argument as &mut *r, creating a fresh, shorter exclusive borrow through r. That new borrow lives for the duration of the call, and r is frozen while it exists. When the call returns, the reborrow ends and r is usable again.
You can see the mechanism by removing the condition that triggers it. Pass the reference somewhere the expected type is a generic parameter rather than a reference type, and the coercion has nothing to hook onto:
fn consume<T>(x: T) -> T { x }
fn main() {
let mut v = vec![1, 2, 3];
let r = &mut v;
consume(r);
consume(r);
}
error[E0382]: use of moved value: `r`
--> src/main.rs:7:13
|
5 | let r = &mut v;
| - move occurs because `r` has type `&mut Vec<i32>`, which does not implement the `Copy` trait
6 | consume(r);
| - value moved here
7 | consume(r);
| ^ value used here after move
|
help: consider creating a fresh reborrow of `r` here
|
6 | consume(&mut *r);
| ++++++
For more information about this error, try `rustc --explain E0382`.
The help line is the whole lesson in one suggestion. Write the reborrow by hand and it works. Reborrowing is not a loophole in the rule, it is the rule applied recursively: at any instant there is still exactly one usable exclusive reference to that vector, it is just that which one it is changes as calls nest and return.
C# has no equivalent question to answer. Passing a ref int onward twice is just two calls, because a ref argument is not a value that can be consumed. C# does have ref locals, ref reassignment, and since C# 11 ref fields inside a ref struct, so references do get stored. What C# never does is track how long any of them are live in the way this section describes. Its ref safety rules ask a narrower question, whether a reference can outlive its storage, and they stop there.
Splitting a borrow, and the three fixes
This is where a C# engineer loses a real afternoon, so it gets a full example.
struct Connection {
id: u32,
bytes_sent: u64,
}
struct Pool {
connections: Vec<Connection>,
log: Vec<String>,
}
impl Pool {
fn record(&mut self, message: String) {
self.log.push(message);
}
fn report(&mut self) {
for conn in &self.connections {
self.record(format!("conn {} sent {}", conn.id, conn.bytes_sent));
}
}
}
Every line of that is the obvious thing to write, and it does not compile.
error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
--> src/main.rs:18:13
|
17 | for conn in &self.connections {
| -----------------
| |
| immutable borrow occurs here
| immutable borrow later used here
18 | self.record(format!("conn {} sent {}", conn.id, conn.bytes_sent));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
For more information about this error, try `rustc --explain E0502`.
Note what it says: *self, not self.log. The loop holds a shared borrow of self.connections, and self.record(..) needs an exclusive borrow of the entire self, because record's signature says &mut self and the checker will not look inside the body to see that it only touches self.log. Borrow checking is function-local by design. Signatures are the contract; bodies are not.
This is worth stating flatly because it is the deepest structural difference between the two languages' error messages. A C# method taking this is opaque and always was, so nobody thinks about it. A Rust method taking &mut self is opaque and the opacity is enforced, so the coarseness of your signatures becomes an ergonomics problem in a way it never was in C#.
Three fixes, all ordinary refactors. Here is a complete program with all three, which compiles and runs:
use std::mem;
struct Connection {
id: u32,
bytes_sent: u64,
}
struct Pool {
connections: Vec<Connection>,
log: Vec<String>,
}
impl Pool {
// Fix 1: touch the two fields directly. They are disjoint places,
// so the compiler tracks them separately.
fn report_inline(&mut self) {
for conn in &self.connections {
self.log
.push(format!("conn {} sent {}", conn.id, conn.bytes_sent));
}
}
// Fix 2: the helper takes only what it needs, not all of self.
fn record(log: &mut Vec<String>, message: String) {
log.push(message);
}
fn report_split(&mut self) {
for conn in &self.connections {
Pool::record(
&mut self.log,
format!("conn {} sent {}", conn.id, conn.bytes_sent),
);
}
}
fn record_method(&mut self, message: String) {
self.log.push(message);
}
// Fix 3: move the field out, work on it, put it back.
fn report_take(&mut self) {
let conns = mem::take(&mut self.connections);
for conn in &conns {
self.record_method(format!("conn {} sent {}", conn.id, conn.bytes_sent));
}
self.connections = conns;
}
}
fn main() {
let mut pool = Pool {
connections: vec![
Connection { id: 1, bytes_sent: 4096 },
Connection { id: 2, bytes_sent: 128 },
],
log: Vec::new(),
};
pool.report_inline();
pool.report_split();
pool.report_take();
for line in &pool.log {
println!("{line}");
}
println!("{} connections still here", pool.connections.len());
}
Output:
conn 1 sent 4096
conn 2 sent 128
conn 1 sent 4096
conn 2 sent 128
conn 1 sent 4096
conn 2 sent 128
2 connections still here
Fix 1 is usually correct and usually the least popular, because it means inlining a helper you liked. Fix 2 is the one that improves the design: a free or associated function taking &mut Vec<String> states its dependencies honestly, and you can now test it without building a Pool. Fix 3 is the escape hatch. mem::take swaps the field for its Default value, which for a Vec is an empty vector that allocates nothing, so the cost is a few pointer writes. Use it when the loop genuinely needs the whole self, and be aware that if the body panics between the take and the restore, the field stays empty in whatever catches the unwind.
There is a fourth option in the standard library worth knowing, for the case where the two halves are inside one collection rather than in two fields. split_at_mut hands you two exclusive slices of one buffer:
let mut buf = [1u8, 2, 3, 4, 5, 6];
let (left, right) = buf.split_at_mut(3);
left[0] = 9;
right[0] = 8;
println!("{buf:?}"); // [9, 2, 3, 8, 5, 6]
Two live &mut slices refer to disjoint regions of the same array. This does not violate the rule: exclusivity applies to overlapping places. The split is sound because the ranges are provably disjoint, and the proof lives inside an unsafe block in the standard library rather than in the type system. That pattern, a small audited unsafe core exposing a safe API, is how most of the interesting data structures in Rust are built.
ref, out, in, and the ref struct family
The surface resemblance to C#'s reference parameters is real and shallow.
| C# | Nearest Rust | Where the analogy breaks |
|---|---|---|
ref T x | &mut T | C# makes no exclusivity promise. Compute(ref a, ref a) compiles. |
in T x | &T | in forbids the callee writing, not others writing. |
out T x | return the value | Rust returns tuples and Option, so out has no reason to exist. |
ref struct | any type holding a & | C# restricts one family of types; Rust checks every reference. |
The ref row is the one to internalize. ref in C# gives a callee the ability to write to your variable, which is what &mut gives too. What it does not give is any statement about who else can see that storage. You can pass ref to a field while three other objects hold references to the containing instance, and nothing checks it. That is the freedom that forced the reload in the Compute example.
out is more interesting than it looks, because its existence is a symptom. C# grew out and then the TryParse convention because returning two values is awkward in a language without cheap sum types. Rust returns Option<T> or Result<T, E> and a tuple when it needs more, so the pattern never formed. If you find yourself reaching for an out parameter in Rust, you want a tuple or an enum.
The closest C# has come to Rust's model is the ref struct family. Span<T> cannot be a field of a class, cannot be an array element, cannot be boxed, and cannot be captured in a lambda. Those restrictions exist for exactly the reason Rust's borrows exist: a Span<T> may point at a stack frame or into the interior of an object, and the compiler has to be certain it cannot outlive what it points at.
The rules there are version dependent and have loosened. Before C# 13 a ref struct could not appear in an async method at all, could not be used in iterators, could not implement interfaces, and could not be a type argument. C# 13 relaxed all four with conditions: a ref struct variable may not be used in the same block as an await expression, may not sit in a code segment containing yield return, may implement interfaces but never be converted to one, and may be a type argument only where the parameter declares allows ref struct. Note what the compiler is checking in all of that. It is checking lifetime, whether a reference can outlive its storage. It never asks whether two live references overlap. The rest, when a span is safe to hand around and when it is stale, is prose in Microsoft's usage guidelines that a human is expected to follow.
If you have ever been annoyed that you cannot stash a Span<T> somewhere convenient, you have already met the borrow checker. You met it in one corner of C# instead of everywhere, and you probably concluded the restriction was about Span<T> rather than about references in general.
At scale
None of this bites hard in a 300 line program. It bites in the shape of the systems you end up building.
The pressure shows up first as signature design. In a service where request handlers reach into a shared state object, every &mut self method on that object becomes a lock on the whole object for the duration of the call. Coarse methods that were harmless in C# become a source of daily friction, and the codebase drifts toward small structs with narrow methods and free functions that take the two or three fields they need. That drift is a genuine design improvement, and it is also a real cost you pay in refactoring time before you get there.
The second pressure is the pull toward indices. When a data structure has internal cross-references, the honest Rust answer is often to stop using references and store integer keys into a Vec or a slot map, which restores the aliasing you wanted while keeping the checker satisfied, at the price of the compiler no longer proving that a key is valid. That is a real tradeoff, not a trick: you swapped a compile-time guarantee for a runtime one. The Rust compiler itself is built this way, leaning on arenas and index types rather than pointer graphs (memory management in rustc), and so is essentially every entity-component system in the ecosystem.
The third shows up when concurrency arrives, and it is the one that makes the earlier work pay. Because the compiler already tracks who may mutate what, sharing across threads is checked by the same machinery. A List<T> handed to two threads in C# is a code review problem. In Rust, sharing a mutable collection across threads requires a type and synchronization strategy that satisfy Send and Sync; unprotected patterns that violate those requirements are rejected in safe code.
The mistakes that are specific to you
Cloning to make the error go away. Some borrow errors can be resolved by cloning, and for a small String in a cold path that can be a reasonable choice. The mistake is doing it reflexively, discovering three months later that a hot loop clones a Vec per iteration, and concluding Rust is slow. Rule of thumb: clone deliberately, in cold code, with a comment saying why. If you clone the same value in a loop, that is the signal to restructure.
Reading &mut as "writable". The root of more confusion than anything else here. When you cannot see why a &mut was rejected, re-read it as "the only reference right now" and the answer usually appears.
Expecting the compiler to look inside a function body. You know your &mut self method only touches one field. The checker does not, and will not, because it checks each function against signatures alone. Fix the signature, not the body.
Holding a reference across a mutation because C# let you. The first = &data[0] then push shape. C# usually hides the problem, because you copied the element rather than pointing at it, and because the collector will not free anything you can still reach. The one place C# lets you make the same mistake is instructive. Take a span over a list's buffer with CollectionsMarshal.AsSpan, add an element that forces a resize, then write through the span. On .NET 9.0.10 the list keeps its original contents, the write lands in the orphaned old array, and nothing throws:
using System.Runtime.InteropServices;
var list = new List<int>(3) { 1, 2, 3 };
var span = CollectionsMarshal.AsSpan(list);
list.Add(4); // capacity 3 to 6, new backing array
span[0] = 99; // writes into the old one
Console.WriteLine($"{list[0]} {span[0]}"); // prints: 1 99
Memory safe, silently wrong, and no diagnostic anywhere. That is the shape the borrow checker exists to reject. Retrain on the reallocation: any method that can grow a collection can move its buffer.
Assuming a getter is free. The aside above. If a struct is fighting you, count how many of its accessors return references to fields, and consider whether those fields could simply be visible within the module.
Where the rule stops helping
Any structure with genuine shared mutable state is harder in Rust, and sometimes meaningfully harder. A cyclic object graph, an observer list where the observers hold back-references to the subject, a cache that several subsystems mutate. In C# you write it and move on. In Rust you reach for reference counting plus interior mutability, and Rc<RefCell<T>> moves the one-writer-or-many-readers check to run time, where a violation is a panic rather than a compile error. You have re-created the C# situation with worse ergonomics and a sharper failure mode. If that is the shape of your problem, C# is the better tool and saying so is not disloyalty.
The checker is also conservative. It rejects programs that are perfectly sound, and you will meet a few: some self-referential structures, some loops where a human can see the borrow ends but the analysis cannot, and the well-known one where a function conditionally returns a reference derived from an argument. That last shape is documented as a limitation by the compiler team, complete with a worked last_or_push example, and fixing it is the stated goal of the polonius work (NLL fully stable). Until then the workaround is a redundant let, which is annoying and harmless.
The standard library papers over the common cases with audited unsafe code, split_at_mut being the visible example, and that option is open to you too. Reaching for it is the intended design rather than a defeat: a small verified core, a large safe surface.
And the guarantee has a boundary. The borrow checker reasons about safe Rust. Cross an FFI boundary into a C library and nobody is checking that the pointer you handed over is not stashed somewhere. Rust does not make that safe. Unsafe operations have to be contained in an unsafe context, but a safe wrapper can expose them to callers. The wrapper's implementer must uphold its safety invariants, so review needs to follow the boundary as well as the keyword.
Checking yourself
Why does &mut exclude even shared borrows, when two readers and one writer sounds survivable? Because conflicting accesses during an exclusive borrow can observe a mutation in progress or retain a reference invalidated by reallocation. The guarantee also enables optimizations, but its exact lowering to compiler attributes is an implementation detail. Reborrows and interior-mutability types have their own rules.
A method call has no ampersand in it. What did it borrow? Whatever its receiver signature says. &self takes a shared borrow of the whole receiver, &mut self an exclusive one, self consumes it. The call site does not show which, which is why coarse &mut self methods cause borrow errors in code that looks innocent.
Why does pool.connections behave differently from pool.connections()? Direct field access borrows one place, so a disjoint field stays free. A getter borrows all of *self, because borrow checking is function-local and the signature is the only thing it reads. Same output, different constraint.
You need to iterate a field while calling a &mut self method. What are your options? Inline the field accesses so the borrows stay disjoint, narrow the helper to take only the field it needs, or mem::take the field out and put it back. The middle one usually leaves the code better than you found it.
Where would you not use this model? Shared mutable graphs often need more design work in Rust. Rc<RefCell<T>> is one single-threaded option, moving borrow checks to runtime; arenas, indices, or other ownership designs are alternatives. Which tradeoff is best depends on the graph and workload.
Get the next deep dive by email
New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.
You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.
Written by Zeeshan Adil
I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.