Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    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.

    About 25 minutesBeginner

    On this page
    1. Concept map
    2. & lends a value
    3. &mut lends it for changing
    4. Many readers or one writer
    5. References can’t dangle
    6. * reads through a reference
    7. Which one should I use?
    8. Under the hood
    9. Common pitfalls
    10. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Passing an object to a functionShares it; the function can read and change itA 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 valueNo 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 variableNot possible for a local number or string; wrap it in an objectref parameter, marked ref at the call site too&mut T parameter, passed as &mut x
    Two writers to one value at the same timeAllowedAllowed, even with refCompile error E0499
    Changing a list while something reads itAllowed; a for…of loop sees the new itemsThrows InvalidOperationException at run timeCompile error E0502
    A reference that outlives its valueImpossible; the GC keeps the value aliveImpossible for objects (GC); ref locals are checked by ref-safety rulesCompile 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”.

    TypeScript
    account.ts
    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);
    C#
    Account.cs
    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;
    }
    Rust
    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.

    TypeScript
    deposit.ts
    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}`);
    C#
    Deposit.cs
    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);
    Rust
    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:

    TypeScript
    scores.ts
    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);
    C#
    Scores.cs
    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);
    }
    Rust
    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 here

    TypeScript 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:

    Two &mut borrows of total at once
    Two &mut borrows of total at once. Each column is a value or a borrow; a mark means it's alive on that line.
    LineCodetotalownerfirstmutable borrow (&mut)secondmutable borrow (&mut)What happens
    1let mut total = 0;ownstotal starts
    2let first = &mut total;total alive&mutfirst starts
    3let second = &mut total;total alivefirst alive&mutsecond startserrorE0499: a second &mut while first is still alive (it's used on line 4)
    4*first += 1;total alivefirst endssecond aliveLast use of first
    5*second += 1;total endssecond 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:

    The shared borrow ends before push
    The shared borrow ends before push. Each column is a value or a borrow; a mark means it's alive on that line.
    LineCodescoresownerfirstshared borrow (&)&mut scoresmutable borrow (&mut)What happens
    1let mut scores = vec![10, 20, 30];ownsscores starts
    2let first = &scores[0];scores alive&first starts
    3println!("first: {first}");scores alivefirst endsLast use of first: the shared borrow ends here
    4scores.push(40); // fine: `first` isn't used after thisscores alive&mut&mut scores startsOK: push borrows scores mutably, and no other borrow is alive
    5println!("{}", 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
    The shared borrow is still alive at push
    The shared borrow is still alive at push. Each column is a value or a borrow; a mark means it's alive on that line.
    LineCodescoresownerfirstshared borrow (&)&mut scoresmutable borrow (&mut)What happens
    1let mut scores = vec![10, 20, 30];ownsscores starts
    2let first = &scores[0];scores alive&first starts
    3scores.push(40); // error: first is still used belowscores alivefirst alive&mut&mut scores startserrorE0502: push needs &mut scores, but first is still alive
    4println!("first: {first}");scores alivefirst endsLast use of first
    5println!("{}", 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 here

    name 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
    counter.ts
    // 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);
    C#
    Counter.cs
    var count = 0;
    Increment(ref count);
    Increment(ref count);
    Console.WriteLine(count);
    
    static void Increment(ref int count) => count++;
    Rust
    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.balance and account.owner.len() work whether account is an Account, a &Account or a &mut Account. That’s why describe and deposit above have no *.
    • println! and format! 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.

    WhatWhenWhyHow
    &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());
    After let reference = &nameOn the stack, name is a String holding a pointer to a heap buffer with the bytes A, d, a, a length of 3 and a capacity of 3. Below it, reference is a &String: a single pointer to the name variable on the stack, not to the heap buffer. Nothing was copied, and name is still the owner.StackHeapname: Stringptrlen3capacity3reference: &Stringptrheap bufferAda
    After let reference = &name. On the stack, name is a String holding a pointer to a heap buffer with the bytes A, d, a, a length of 3 and a capacity of 3. Below it, reference is a &String: a single pointer to the name variable on the stack, not to the heap buffer. Nothing was copied, and name is still the owner.

    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.

    Starting code in TypeScript
    withdraw.ts
    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)}`);
    }
    Starting code in C#
    Withdraw.cs
    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.