liveBook · Manning

Reference

As explained in Learn Rust in a Month of Lunches

An immutable reference is a Rust reference through which the referent cannot be modified and which can coexist with other immutable references.

An immutable reference lets code view a value without changing it. Write one with the reference operator, as in `let number_ref = &number;`. Because it only provides access for reading, many immutable references can safely exist at the same time. section 2.10 section 2.5.1

Remember these reference rules:

  • Create as many immutable references as needed; one, three, or even 1,000 are allowed because they only view the data. section 2.5.1 section 2.5.3
  • Do not combine an immutable reference with a mutable reference to the same data while both are in use. section 2.5.1 section 2.5.4
  • Let the mutable borrow finish before creating or using an immutable reference; Rust can recognize when the mutable reference is no longer used. section 2.5.4

Sharing a value safely

Imagine presenting data to 100 people. Everyone can receive an immutable reference and look at the presentation, while nobody can alter it. The same remains safe if many more viewers arrive. By contrast, allowing someone with a mutable reference to change the presentation while others read it could produce unexpected results, so Rust rejects that overlap. section 2.5.3 section 2.5.4

fn main() {
    let mut number = 10;
    let number_ref = &number;
    let number_change = &mut number;
    *number_change += 10;
    println!("{}", number_ref);
}

Inspect the Rust example that changes `number` through a mutable reference and then tries to use an immutable reference. The adjacent compiler feedback identifies the conflicting borrow; rearranging the operations allows the code to work. section 2.5.4

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains sharing rules, mixed-borrow errors, and compiler reasoning about when a mutable borrow ends.
Examples
Uses a presentation analogy, a shared-viewer scenario, and Rust code that triggers and then avoids a borrow conflict.
What you can do after
Evaluate borrow arrangements and reorder operations to avoid conflicting mutable and immutable references.
How it connects
Connects immutable references with mutable references, borrowing, ownership, and compiler borrow checking.

Also explained in

Compare how 3 books explain reference →

Related concepts

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