liveBook · Manning

Reference

As explained in Refactoring to Rust

An immutable reference is a Rust non-owning reference that permits access to a value without modifying it through that reference.

An immutable reference is a non-owning way to access a Rust value without modifying it through that reference. Borrowing lets a function use a value temporarily while leaving ownership with its owner. section 2.3.1

Use an immutable reference when a function only needs to inspect a value. Passing a reference avoids moving the owned value, so the same artwork can be admired repeatedly and its memory can be reused. section 2.3.1

Keep these borrowing rules in view:

  • Write &T for an immutable reference to a value of type T. section 2.3.1
  • Allow any number of immutable references at one time, or exactly one mutable reference, but not both kinds together. section 2.3.1 section 2.3.2
  • Keep references valid, and recognize that a reference ends when its scope ends. section 2.3.1 section 2.3.2
  • Read &T in a function signature as a guarantee that the function views the value rather than modifying it through that reference. section 2.3.2

Admiring the same artwork twice

Define `fn admire_art(art: &Artwork)` and call it with `&art1` twice. The function borrows `art1`, prints its name, and returns it without taking ownership. If the function must increment a view counter instead, change the parameter to `&mut Artwork` and pass `&mut art1`; that requires `art1` to be mutable. section 2.3.1 section 2.3.2

Listing 2.9 A program admiring the same art twice
struct Artwork {
  name: String,
}

fn admire_art(art: &Artwork) {  #1
  println!("Wow, {} really makes you think.", art.name);
}

fn main() {
  let art1 = Artwork { name: "The Ordeal of Owain".to_string() };

  admire_art(&art1);  #2
  admire_art(&art1);
}

Inspect the complete Rust program that borrows one Artwork through an immutable reference and passes it to admire_art twice. section 2.3.1

How Refactoring to Rust covers it

How deep it goes
Explains &T, borrowing rules, scope, and the contrast with &mut T through small artwork programs.
Examples
Demonstrates repeated artwork admiration and contrasts it with a mutable view counter.
What it assumes
Builds from ownership and moved values while introducing borrowing rules through concrete function calls.
What you can do after
Apply immutable references by changing owned parameters to &T and passing borrowed values without moving them.
How it connects
Connects immutable references with borrowing, ownership, mutability, mutable references, and lifetimes.

Also explained in

Compare how 3 books explain 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.