rsRustPrimer
< Back to module

Ownership and borrowing

References and borrowing

A reference lets you access a value without owning it: we say we borrow it. &x creates a read-only reference, &mut x a reference that allows modification.

rust
fn name_length(name: &String) -> usize {
name.len()
}
fn add_suffix(name: &mut String) {
name.push_str(" (CCP)");
}
fn main() {
let mut counterparty = String::from("LCH");
let len = name_length(&counterparty); // emprunt en lecture
add_suffix(&mut counterparty); // emprunt en écriture
println!("{counterparty} ({len} caractères au départ)");
}
main stays the owner from start to finish. Functions borrow, then give control back.

The borrow checker's golden rule: at any given time, you can have either as many & references as you like, or a single &mut reference, but never both at once. Many readers, or one writer.

rust
fn main() {
let mut rates = vec![0.01, 0.02];
let first = &rates[0]; // emprunt en lecture
// rates.push(0.03); // erreur : cannot borrow as mutable
println!("{first}"); // dernier usage de first
rates.push(0.03); // ok : l'emprunt en lecture est terminé
println!("{rates:?}");
}
Why forbid it? push may reallocate the vector elsewhere in memory, and first would then point to nothing. In Java this is a ConcurrentModificationException at runtime; here, a compile error.

Your turn

Write apply_shock, which multiplies every rate in the vector by (1 + shock), modifying the vector in place.

src/main.rs
fn apply_shock(/* paramètres */) {
todo!()
}
fn main() {
let mut rates = vec![0.010, 0.020, 0.030];
apply_shock(&mut rates, 0.5);
println!("{rates:?}"); // environ [0.015, 0.03, 0.045]
}