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



