liveBook · Manning

Borrowing

As explained in Refactoring to Rust

Rust's borrowing rules constrain the number, mutability, and validity of references to a value.

Borrowing lets Rust code use a value without taking ownership of it. A borrow produces a reference: a value that tells Rust how to find the borrowed value. The owner remains responsible for the value, and the reference must not outlive it. section 2.1 section 2.3.1

Borrowing follows two rules:

  • A value may have either one mutable reference or any number of immutable references at a time. section 2.3.1
  • References must always be valid. section 2.3.1

These rules matter when a function needs to use a value more than once. Passing an owned Artwork to admire_art moves it into the function, so a second call with the same value fails to compile. Instead, change the parameter to &Artwork and pass &art1 on each call. Each call borrows the artwork rather than taking ownership. section 2.1 section 2.3.1

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);
}

See the borrowed parameter and both calls using &art1. section 2.3.1

Creating a reference from a raw pointer requires extra care. Check that the pointer is nonnull and points to an initialized, valid value; the reference must also have a valid lifetime and obey borrowing rules. In particular, other code must not mutate the pointed-to contents while Rust holds an immutable reference to them. section 4.4

Borrowing an NGINX request

An NGINX request handler checks its request pointer for null before converting it to an immutable reference. The conversion also relies on the request being initialized and NGINX not modifying it in the background. A generic lifetime ties the returned request-body string slice to the request reference. section 4.4

How Refactoring to Rust covers it

How deep it goes
Explains reference rules and a worked borrowing refactor, then applies validity and lifetime checks to unsafe pointer conversion.
Examples
Uses repeated artwork viewing and an NGINX request-body handler to illustrate borrowing.
What it assumes
Introduces ownership and borrowing as Rust basics before integrating a Rust library into an application written in another language.
What you can do after
Apply borrowing in Rust function signatures and evaluate reference validity when converting foreign pointers.
How it connects
Connects borrowing with ownership, references, mutability, lifetimes, raw pointers, and foreign function interfaces.

Also explained in

Compare how 4 books explain borrowing →

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.