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


