A mutable reference (&mut) lets a function change a value the caller owns. Dereferencing with * reaches the value.

Program

Play the program to add a bonus to total through a mutable reference.

mutable_borrow.rs
Replay: real traced execution (multi-file project)
fn main() {
    let mut total = 10;
    add_bonus(&mut total);
    println!("{total}");
}

fn add_bonus(value: &mut i32) {
    *value += 5;
}
  1. total ← 10

    1fn main() {2    let mut tota→ 10l = 10;3    add_bonus(&mut tota10l);4    println!("{total}");
  2. value ← 15, total ← 15

    2    let mut total = 10;3    add_bonus(&mut tota→ 15l);4    println!("{total}");5}67fn add_bonus(value: &mut i32) {8    *valu→ 15e += 5;9}
    output15

Follow the Change

  1. total starts at 10 and is owned by main.
  2. &mut total gives add_bonus temporary permission to change it.
  3. *value += 5 changes the caller's total.
  4. After the call ends, main can read total again.
main owns total: 10
add_bonus borrows it: &mut total
after the borrow: 15
&mut `&mut total` hands out a mutable reference.
dereference `*value` reaches the value the reference points to.
in-place change The owned `total` reflects the change after the call.

Exercise: mutable_borrow.rs

Write a helper that takes &mut i32, changes the value once, and print the value after the borrow ends