# 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#.

- Author: Zeeshan Adil (https://www.internalswithzee.com/about)
- Published: 2026-09-06
- Updated: 2026-11-21
- Source: https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers/rust-borrowing-and-the-borrow-checker

Chapter 5 of 16 of [Rust for C# Engineers: From Garbage Collection to Ownership and Lifetimes](https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers.md). Part I, Foundations.

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.

```rust
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.

**Why this first example uses &String**

An ordinary read-only string parameter should usually be `&str`, which also accepts borrowed views of a `String` and string literals. This example uses `&String` to make the borrow visible beside a familiar type. Also, `len()` counts UTF-8 bytes, not characters; the counts happen to match for the ASCII text `db-1`.

![The binding name owns a String. The function length_of reads that same String through a shared reference without taking ownership. After the call, name remains the owner and can be used again.](https://www.internalswithzee.com/images/diagrams/rust-shared-borrow-wide.svg)

## What the rule actually says

There are two kinds.

- `&T` is a shared borrow. Multiple shared borrows may overlap; ordinary mutation through them is prohibited, with interior-mutability types providing controlled exceptions.
- `&mut T` is 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](https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html)). 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.

**Definition: Aliasing**

Two pointers alias when they refer to the same memory. Aliasing on its own is harmless, and C# does it constantly: two variables pointing at one `List`, a field and a local both holding the same object, a `ref` parameter pointing at a field somebody else can also reach.

Aliasing plus mutation is where the trouble is. If one path can write while another reads, you get torn reads, invalidated iterators, and across threads, data races. Compilers also have to assume the worst about aliased pointers, which blocks whole classes of optimization.

Rust controls conflicting access in safe code rather than banning aliases or mutation altogether. Interior-mutability types such as `Cell` and `Mutex` deliberately allow controlled mutation through shared references; `&mut` also supports shorter reborrows. The details matter when you move from this introductory model to unsafe code.

## 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.

```csharp
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:

```csharp
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`](https://en.cppreference.com/w/c/language/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:

```rust
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}");
}
```

```text
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](https://llvm.org/docs/LangRef.html#parameter-attributes)). 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](https://doc.rust-lang.org/nomicon/aliasing.html) has the clearest short list, and it uses a version of the same `compute` function to make the point.

This one has an embarrassing history that is worth knowing, because it is the honest version of the zero-cost claim.

Rust emitted `noalias` for `&mut`, LLVM had miscompilation bugs that the annotation exposed, and rustc switched it off. It stayed off for years. It came back on by default in [Rust 1.54, released 29 July 2021](https://blog.rust-lang.org/2021/07/29/Rust-1.54.0/), and only when building against LLVM 12 or newer. The [release notes](https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1540-2021-07-29) put it in one line: "`-Zmutable-noalias=yes` is enabled by default when using LLVM 12 or above".

So the optimization existed on paper long before it existed in your binary, and the language shipped for years without the payoff people were already citing. Take the general lesson: aliasing information is worth real cycles in tight numeric and buffer-shuffling code and close to nothing in a service that spends its life waiting on sockets. If someone tells you Rust is faster because of `noalias`, ask what their program actually does and check the generated code and measurements for that workload.

## The bug this is really about

You have hit this in C#, and the compiler let you write it:

```csharp
var servers = new List<string> { "db-1", "db-2" };
foreach (var s in servers)
{
    if (s == "db-1") servers.Add("db-3");
}
```

```text
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` 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](https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/List.cs)). 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:

```csharp
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`, 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.

```rust
fn main() {
    let mut servers = vec!["db-1", "db-2"];
    for s in &servers {
        if *s == "db-1" {
            servers.push("db-3");
        }
    }
}
```

```text
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:

```rust
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.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:

```rust
fn main() {
    let mut data = vec![1, 2, 3];
    let first = &data[0];
    data.push(4);
    println!("{first}");
}
```

```text
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](https://rust-lang.github.io/rfcs/2094-nll.html) 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](https://blog.rust-lang.org/2022/08/05/nll-by-default/). 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.

```rust
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](https://doc.rust-lang.org/reference/expressions/method-call-expr.html). 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:

```rust
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](https://rustc-dev-guide.rust-lang.org/borrow-check/two-phase-borrows.html). 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:

```rust
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:

```rust
fn consume<T>(x: T) -> T { x }

fn main() {
    let mut v = vec![1, 2, 3];
    let r = &mut v;
    consume(r);
    consume(r);
}
```

```text
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.

```rust
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.

```text
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:

```rust
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:

```text
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` 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`](https://doc.rust-lang.org/std/primitive.slice.html#method.split_at_mut) hands you two exclusive slices of one buffer:

```rust
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.

The field-splitting exemption stops at the function boundary in both directions, and the second direction catches people. Accessing `self.connections` directly is a borrow of one field. Calling a getter `self.connections()` that returns `&Vec` is a borrow of all of `self`, even though the two look nearly identical at the call site and the getter will almost certainly inline away in a release build.

Loop over `pool.connections()` while pushing to `pool.log` and rustc reports `cannot borrow pool.log as mutable because it is also borrowed as immutable`, with the immutable-borrow annotation sitting on the getter call rather than on any field. The call is what borrows, and what it borrowed was the whole receiver. Swap the call for `&pool.connections` and the same loop compiles. This is the main reason idiomatic Rust has fewer getters than idiomatic C#. Encapsulation that costs you nothing in C# costs you borrow granularity here.

## `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#](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref) 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` or `Result` 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` [cannot be a field of a class, cannot be an array element, cannot be boxed, and cannot be captured in a lambda](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/ref-struct). Those restrictions exist for exactly the reason Rust's borrows exist: a `Span` 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](https://learn.microsoft.com/en-us/dotnet/standard/memory-and-spans/memory-t-usage-guidelines) that a human is expected to follow.

If you have ever been annoyed that you cannot stash a `Span` 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` 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](https://rustc-dev-guide.rust-lang.org/memory.html)), 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` 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`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.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:

```csharp
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](https://doc.rust-lang.org/book/ch15-05-interior-mutability.html), and `Rc>` 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](https://rust-lang.github.io/polonius/) work ([NLL fully stable](https://blog.rust-lang.org/2022/08/05/nll-by-default/)). 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>` 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.

Previous: [Ownership, and the rule that replaced the collector](https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers/rust-ownership-and-moves.md)
Next: [Lifetimes are not object lifetime](https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers/rust-lifetimes-explained.md)
