liveBook · Manning

Mutable reference

As explained in Refactoring to Rust

A mutable reference is a Rust non-owning reference that permits modification of the referenced value under Rust's aliasing rules.

A mutable reference, written &mut T, temporarily borrows a value and permits its modification without taking ownership. Rust allows either one mutable reference or any number of immutable references at a time, and references must remain valid. section 2.3.1 section 2.3.2

Use the reference type to make a function’s permitted behavior explicit:

  • &Artwork lets a function inspect artwork repeatedly without moving or recreating the owned value. section 2.3.1
  • &mut Artwork lets a function update artwork, but the owner must be declared mutable and passed with &mut. section 2.3.2
  • Sequential calls remain legal because each mutable reference ends when the function returns; no two mutable references overlap. section 2.3.2

Incrementing a view counter

Define admire_art as fn admire_art(art: &mut Artwork), increment art.view_count inside it, declare the owner as let mut art1, and call admire_art(&mut art1) twice. section 2.3.2

Listing 2.11 Incrementing a view counter on an artwork using mutable references
struct Artwork {
  view_count: i32,
  name: String,
}

fn admire_art(art: &mut Artwork) { #1
  println!("{} people have seen {} today!",
    art.view_count, art.name);
  art.view_count += 1;  #2
}

fn main() {
  let mut art1 = Artwork {
    view_count: 0, name: "".to_string() };  #3

  admire_art(&mut art1);  #4
  admire_art(&mut art1);
}

Inspect the complete mutable-reference example, including the Artwork type, function signature, mutation, mutable owner, and calls. section 2.3.2

How Refactoring to Rust covers it

How deep it goes
Explains syntax, ownership-preserving borrowing, aliasing rules, and scope-based validity through an incremental artwork example.
Examples
Demonstrates repeated artwork viewing and an incrementing view counter implemented with borrowed references.
What it assumes
Assumes basic variables and functions, while introducing ownership-preserving borrowing and controlled mutability incrementally.
What you can do after
Apply mutable references to write functions that modify borrowed structs while respecting Rust’s exclusive-aliasing rules.
How it connects
Ties mutable references to ownership, borrowing, mutability, immutable references, and lifetimes.

Also explained in

Compare how 3 books explain mutable reference →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.