Module 3 · Borrowing & slices
3.1References: &T and &mut T
How Rust lends a value without giving it away, why you can have many readers or one writer but never both, and what & and * really mean.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| Passing an object to a function | Shares it; the function can read and change it | A class is shared; a struct is copied unless you pass it with ref or in | &T lends it to read; &mut T lends it to change; the caller keeps ownership |
& in front of a value | No such operator (only bitwise AND) | Address-of, in unsafe code only (and bitwise AND) | A borrow, checked by the compiler. Not a raw address. |
| Changing a caller's variable | Not possible for a local number or string; wrap it in an object | ref parameter, marked ref at the call site too | &mut T parameter, passed as &mut x |
| Two writers to one value at the same time | Allowed | Allowed, even with ref | Compile error E0499 |
| Changing a list while something reads it | Allowed; a for…of loop sees the new items | Throws InvalidOperationException at run time | Compile error E0502 |
| A reference that outlives its value | Impossible; the GC keeps the value alive | Impossible for objects (GC); ref locals are checked by ref-safety rules | Compile error E0597 |
In the last module you saw that passing a String or a Vec to a function moves it: the function owns it, and you can’t use it afterwards. That’s rarely what you want for a function that only looks at a value. Rust’s answer is to lend it. A reference, written &value, gives the function access for the duration of the call, and ownership stays with you. The compiler checks every loan, so a reference can never outlive its value or collide with a change to it.
& lends a value
Here’s a function that reads an account and builds a sentence about it. In TypeScriptC#, the function receives a reference to the caller’s object. In Rust, it receives a borrow: &Account means “a reference to an Account that someone else owns”.
type Account = { owner: string; balance: number };
function describe(account: Account): string {
return `${account.owner} has ${account.balance}`;
}
const account: Account = { owner: "Ada", balance: 100 };
console.log(describe(account));
console.log(account.owner);var account = new Account("Ada", 100);
Console.WriteLine(Describe(account));
Console.WriteLine(account.Owner);
static string Describe(Account account) => $"{account.Owner} has {account.Balance}";
class Account(string owner, int balance)
{
public string Owner { get; } = owner;
public int Balance { get; set; } = balance;
}struct Account {
owner: String,
balance: i64,
}
fn describe(account: &Account) -> String {
format!("{} has {}", account.owner, account.balance)
}
fn main() {
let account = Account {
owner: String::from("Ada"),
balance: 100,
};
println!("{}", describe(&account));
println!("{}", account.owner); // still ours: we only lent it
}Output
Ada has 100 Ada
&account at the call site creates the reference, and &Account in the signature accepts one. Inside describe, you use account.owner exactly as you would with an owned value. When the call returns, the loan ends and main still owns account.
Mental model shift& means borrow, not address-of
In TypeScript, & is only bitwise AND, and there’s no way to point at a variable at all; an object variable just holds a reference the garbage collector tracks.In C#, &x takes a raw address in unsafe code. Rust’s &x is a borrow: at run time it’s a plain pointer, but you can’t do arithmetic on it, it’s never null, and the compiler proves it points at a live value for as long as you use it. A shared reference &T is also read-only: describe can’t change the account it was lent.
&mut lends it for changing
A shared reference can’t change anything. To let a function modify the caller’s value, lend it with &mut. The closest C# feature is a ref parameter, and like ref, Rust makes you write it at the call site too, so a reader can see which arguments might change.
type Account = { owner: string; balance: number };
function deposit(account: Account, amount: number): void {
account.balance += amount;
}
const account: Account = { owner: "Ada", balance: 100 };
deposit(account, 50);
console.log(`${account.owner} has ${account.balance}`);var account = new Account("Ada", 100);
Deposit(ref account, 50);
Console.WriteLine($"{account.Owner} has {account.Balance}");
static void Deposit(ref Account account, int amount) => account.Balance += amount;
record struct Account(string Owner, int Balance);struct Account {
owner: String,
balance: i64,
}
fn deposit(account: &mut Account, amount: i64) {
account.balance += amount;
}
fn main() {
let mut account = Account {
owner: String::from("Ada"),
balance: 100,
};
deposit(&mut account, 50);
println!("{} has {}", account.owner, account.balance);
}Output
Ada has 150
The C# version uses a record struct, so without ref the method would change a copy.In TypeScript, every object parameter can be changed by the function, and nothing in the signature says so. In Rust, mut shows up three times, and each one is a separate permission:
let mut account: this variable’s value may change.&mut account: lend it with permission to change it.account: &mut Account: this function expects that permission.
Many readers or one writer
Here’s the rule the compiler enforces for every reference, often called aliasing XOR mutability. At any moment, a value can have either:
- any number of shared references (
&T), or - exactly one mutable reference (
&mut T),
but never both. While a &mut exists, nothing else can read or write the value; while any &T exists, nothing can change it.
That rule rules out a whole family of bugs. The classic one is changing a collection while you loop over it:
const scores = [10, 20, 30];
for (const score of scores) {
if (score === 20) {
scores.push(score * 2); // the loop will visit 40 too
}
}
console.log(scores.length);var scores = new List<int> { 10, 20, 30 };
try
{
foreach (var score in scores)
{
if (score == 20)
{
scores.Add(score * 2);
}
}
}
catch (InvalidOperationException error)
{
Console.WriteLine(error.Message);
}let mut scores = vec![10, 20, 30];
for score in &scores {
if *score == 20 {
scores.push(score * 2);
}
}Rust doesn't compile this: error E0502
error[E0502]: cannot borrow `scores` as mutable because it is also borrowed as immutable
--> scores.rs:4:9
|
2 | for score in &scores {
| -------
| |
| immutable borrow occurs here
| immutable borrow later used here
3 | if *score == 20 {
4 | scores.push(score * 2);
| ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs hereTypeScript runs the loop over a list that changes under it.C# notices at run time and throws “Collection was modified”. Rust refuses to compile: the loop holds a shared borrow of scores (&scores) until it ends, and push needs a mutable one. Without a garbage collector, the bug would be worse than a surprise extra loop passan exception: push can move the vector’s buffer to a bigger allocation, and the loop would go on reading the freed one.
Two mutable borrows at once fail too, with a different code:
let mut total = 0;
let first = &mut total;
let second = &mut total;
*first += 1;
*second += 1;Rust doesn't compile this: error E0499
error[E0499]: cannot borrow `total` as mutable more than once at a time --> main.rs:3:14 | 2 | let first = &mut total; | ---------- first mutable borrow occurs here 3 | let second = &mut total; | ^^^^^^^^^^ second mutable borrow occurs here 4 | *first += 1; | ----------- first borrow later used here
Line by line, the two mutable borrows overlap on lines 3 and 4:
| Line | Code | totalowner | firstmutable borrow (&mut) | secondmutable borrow (&mut) | What happens |
|---|---|---|---|---|---|
| 1 | let mut total = 0; | ownstotal starts | |||
| 2 | let first = &mut total; | total alive | &mutfirst starts | ||
| 3 | let second = &mut total; | total alive | first alive | &mutsecond starts | errorE0499: a second &mut while first is still alive (it's used on line 4) |
| 4 | *first += 1; | total alive | first ends | second alive | Last use of first |
| 5 | *second += 1; | total ends | second ends |
A timeline of the five lines above. total owns the number from line 1 to line 5. first, a mutable borrow, starts on line 2 and lasts until its last use on line 4. second, another mutable borrow, starts on line 3 and lasts until line 5. On line 3 both mutable borrows are alive at once, and the compiler rejects that line with E0499.
In TypeScript, any number of names can change the same object at the same time.In C#, ref int first = ref total; ref int second = ref total; compiles, and both change the same variable. Rust allows only one writer, so the compiler can assume no one else changes a value behind a &mut.
Caught at compile timeA borrow ends at its last use
A borrow doesn’t last until the closing brace. It lasts until the last line that uses the reference. So this compiles, because first is finished before push runs:
let mut scores = vec![10, 20, 30];
let first = &scores[0];
println!("first: {first}");
scores.push(40); // fine: `first` isn't used after this
println!("{}", scores.len());As a timeline, with one column per value or borrow and a bar for the lines where each is alive:
| Line | Code | scoresowner | firstshared borrow (&) | &mut scoresmutable borrow (&mut) | What happens |
|---|---|---|---|---|---|
| 1 | let mut scores = vec![10, 20, 30]; | ownsscores starts | |||
| 2 | let first = &scores[0]; | scores alive | &first starts | ||
| 3 | println!("first: {first}"); | scores alive | first ends | Last use of first: the shared borrow ends here | |
| 4 | scores.push(40); // fine: `first` isn't used after this | scores alive | &mut&mut scores starts | OK: push borrows scores mutably, and no other borrow is alive | |
| 5 | println!("{}", scores.len()); | scores ends |
A timeline of the five lines above. scores owns the vector from line 1 to line 5. first, a shared borrow, starts on line 2 and ends at its last use on line 3. push needs a mutable borrow of scores on line 4 only. The two borrows never overlap, so the code compiles.
Move the println! of first below the push and you get E0502 again:
let mut scores = vec![10, 20, 30];
let first = &scores[0];
scores.push(40); // error: first is still used below
println!("first: {first}");
println!("{}", scores.len());Rust doesn't compile this: error E0502
error[E0502]: cannot borrow `scores` as mutable because it is also borrowed as immutable
--> main.rs:3:1
|
2 | let first = &scores[0];
| ------ immutable borrow occurs here
3 | scores.push(40); // error: first is still used below
| ^^^^^^^^^^^^^^^ mutable borrow occurs here
4 | println!("first: {first}");
| ----- immutable borrow later used here| Line | Code | scoresowner | firstshared borrow (&) | &mut scoresmutable borrow (&mut) | What happens |
|---|---|---|---|---|---|
| 1 | let mut scores = vec![10, 20, 30]; | ownsscores starts | |||
| 2 | let first = &scores[0]; | scores alive | &first starts | ||
| 3 | scores.push(40); // error: first is still used below | scores alive | first alive | &mut&mut scores starts | errorE0502: push needs &mut scores, but first is still alive |
| 4 | println!("first: {first}"); | scores alive | first ends | Last use of first | |
| 5 | println!("{}", scores.len()); | scores ends |
A timeline of the five lines above. scores owns the vector from line 1 to line 5. first, a shared borrow, starts on line 2 and now lasts until its last use on line 4. push needs a mutable borrow of scores on line 3, while first is still alive, so the compiler rejects line 3 with E0502.
References can’t dangle
A reference must never outlive the value it points at. TypeScriptC# guarantees this with the garbage collector: as long as something points at an object, it stays alive. Rust has no collector, so the compiler checks it instead:
let reference;
{
let name = String::from("Ada");
reference = &name;
} // `name` is dropped here, so `reference` would point at freed memory
println!("{reference}");Rust doesn't compile this: error E0597
error[E0597]: `name` does not live long enough
--> main.rs:4:17
|
3 | let name = String::from("Ada");
| ---- binding `name` declared here
4 | reference = &name;
| ^^^^^ borrowed value does not live long enough
5 | } // `name` is dropped here, so `reference` would point at freed memory
| - `name` dropped here while still borrowed
6 | println!("{reference}");
| --------- borrow later used herename is dropped at the inner closing brace, but reference is used after it. In C or C++ this compiles and reads freed memory. Rust stops it. The span of code where a borrow is valid is called its lifetime. You rarely write lifetimes yourself, because the compiler works them out; Module 11 covers the cases where you have to name them.
* reads through a reference
* is the dereference operator: *r means “the value r points at”. You need it when you read or write a plain value, such as a number, through a reference. Here’s a function that adds one to the caller’s counter:
// TypeScript can't pass a local number by reference, so wrap it in an object.
function increment(count: { value: number }): void {
count.value += 1;
}
const count = { value: 0 };
increment(count);
increment(count);
console.log(count.value);var count = 0;
Increment(ref count);
Increment(ref count);
Console.WriteLine(count);
static void Increment(ref int count) => count++;fn increment(count: &mut i32) {
*count += 1;
}
fn main() {
let mut count = 0;
increment(&mut count);
increment(&mut count);
println!("{count}");
}Output
2
TypeScript can’t lend a number at all, so its version lends an object and changes a field of it.C# hides the dereference: inside Increment, count behaves like the caller’s variable. Rust makes you write *count += 1, because count is the reference and *count is the number.
You’ll write * much less often than you might expect, because Rust dereferences automatically in the common cases:
- Field access and method calls follow references for you:
account.balanceandaccount.owner.len()work whetheraccountis anAccount, a&Accountor a&mut Account. That’s whydescribeanddepositabove have no*. println!andformat!print the value, not the address.
You still need * to assign through a &mut to a whole value (*count += 1) and to compare a reference with a plain value (*score == 20).
Which one should I use?
When a function needs a value, it can borrow it to read, borrow it to change, or take it outright.
| What | When | Why | How |
|---|---|---|---|
&T (shared reference) | The function only reads the value. | No copy, and the caller keeps ownership. Any number of &T can exist at once. This is the most common choice. | Take account: &Account; call describe(&account). |
&mut T (mutable reference) | The function changes the caller’s value in place. | The change is visible to the caller, and the signature and call site both say so. Only one can exist at a time, so nothing else sees a half-done change. | Take account: &mut Account; declare let mut account; call deposit(&mut account, 50). |
T (owned value) | The function keeps the value (stores it, returns it inside something else) or uses it up. | The caller hands it over, so there’s nothing left to borrow-check. Numbers and other Copy types are copied, so taking them by value is cheap. | Take account: Account; call close(account). The caller can’t use account afterwards. |
Rule of thumb: borrow with &T by default, use &mut T only when the function must change the caller’s value, and take T when the function needs to keep it. The third lesson in this module, Choosing parameter types, turns this into a full guide for function signatures.
Under the hood
At run time, a reference to a value like a String or an Account is a pointer: one machine word, 8 bytes on a 64-bit system. (A reference to a slice also carries a length; that’s the next lesson.) &T and &mut T compile to the same thing. All the differences between them, and every rule in this lesson, are checked at compile time and cost nothing when the program runs. There’s no reference count and no lock.
let name = String::from("Ada");
let reference = &name;
println!("{reference} has {} letters", reference.len());reference points at the name variable, not at the text. reference.len() follows it to name and reads the length there. Because name is still the owner, the buffer is freed exactly once, when name goes out of scope, and the compiler made sure reference isn’t used after that.
The part of the compiler that checks these rules is the borrow checker. For each reference, it works out where the borrow starts, where it’s last used, and whether anything else touches the same value in between. If a rule is broken, you get one of the errors above, before the program ever runs.
Common pitfalls
Common pitfall&mut needs a mut variable
You can’t lend something for changing if the variable itself isn’t mutable. Forgetting let mut is the most common borrow error:
let count = 0;
let reference = &mut count;
*reference += 1;Rust doesn't compile this: error E0596
error[E0596]: cannot borrow `count` as mutable, as it is not declared as mutable --> main.rs:2:17 | 2 | let reference = &mut count; | ^^^^^^^^^^ cannot borrow as mutable | help: consider changing this to be mutable | 1 | let mut count = 0; | +++
The fix is let mut count = 0;. The compiler’s message suggests it.
Common pitfallA reference isn't equal to a number
Looping over &scores gives you &i32 values, not i32. Comparing one with a plain number doesn’t compile:
let scores = vec![10, 20, 30];
for score in &scores {
if score == 20 {
println!("found it");
}
}Rust doesn't compile this: error E0277
error[E0277]: can't compare `&{integer}` with `{integer}`
--> main.rs:3:14
|
3 | if score == 20 {
| ^^ no implementation for `&{integer} == {integer}`
|
= help: the trait `PartialEq<{integer}>` is not implemented for `&{integer}`
help: consider dereferencing here
|
3 | if *score == 20 {
| +Dereference it with *score == 20. Arithmetic like score * 2 works without *, because the number operators are also defined for references.
Common pitfall&mut isn't ref
C# ref lets two names change one variable at the same time. Rust’s &mut is exclusive: while it exists, it’s the only way to reach the value. If you’re porting C# that passes the same variable as two ref arguments, the Rust version needs a different shape, usually a function that takes one &mut and returns the result.
C# out parameters have no Rust equivalent. Return the value instead, or a tuple if there are several: fn min_max(scores: &[i32]) -> (i32, i32). For the TryParse pattern, return an Option or a Result (Module 6).
Try it yourself
Exercise: port this to Rust
Port this program to Rust. withdraw should change the caller’s account and report whether it succeeded; describe should only read it.
type Account = { owner: string; balance: number };
function withdraw(account: Account, amount: number): boolean {
if (amount > account.balance) {
return false;
}
account.balance -= amount;
return true;
}
function describe(account: Account): string {
return `${account.owner} has ${account.balance}`;
}
const account: Account = { owner: "Ada", balance: 100 };
for (const amount of [30, 90]) {
const result = withdraw(account, amount) ? "ok" : "declined";
console.log(`${result}: ${describe(account)}`);
}var account = new Account("Ada", 100);
foreach (var amount in new[] { 30, 90 })
{
var result = Withdraw(ref account, amount) ? "ok" : "declined";
Console.WriteLine($"{result}: {Describe(in account)}");
}
static bool Withdraw(ref Account account, int amount)
{
if (amount > account.Balance)
{
return false;
}
account.Balance -= amount;
return true;
}
static string Describe(in Account account) => $"{account.Owner} has {account.Balance}";
record struct Account(string Owner, int Balance);Expected output
ok: Ada has 70 declined: Ada has 70
Show a hint
describe only reads, so it takes &Account. withdraw changes the balance, so it takes &mut Account, and main must declare the account with let mut and pass &mut account.
Show a solution
struct Account {
owner: String,
balance: i64,
}
fn withdraw(account: &mut Account, amount: i64) -> bool {
if amount > account.balance {
return false;
}
account.balance -= amount;
true
}
fn describe(account: &Account) -> String {
format!("{} has {}", account.owner, account.balance)
}
fn main() {
let mut account = Account {
owner: String::from("Ada"),
balance: 100,
};
for amount in [30, 90] {
let ok = withdraw(&mut account, amount);
let result = if ok { "ok" } else { "declined" };
println!("{result}: {}", describe(&account));
}
}withdraw borrows the account mutably for the length of the call and returns a bool, so the caller can print the result and then borrow the account again with &account. Nothing is cloned and main owns the account the whole time.
Saved in this browser only.