Rust Tutorial · Ownership and Borrowing · Lesson 10 of 29
Rust References and Borrowing
Borrow values with & and &mut instead of moving them, and the rules that prevent data races.
Borrowing
A reference lets you use a value without taking ownership: &value (shared, read-only) or &mut value
(exclusive, can modify).
fn total_length(words: &[String]) -> usize {
words.iter().map(|w| w.len()).sum()
}
fn add_word(words: &mut Vec<String>, word: &str) {
words.push(word.to_string());
}
fn main() {
let mut words = vec![String::from("safe"), String::from("fast")];
add_word(&mut words, "concurrent");
println!("{} words, {} letters", words.len(), total_length(&words));
println!("still owned here: {words:?}");
}
Output
3 words, 18 letters still owned here: ["safe", "fast", "concurrent"]
Run this on your computer — see “Get Started” for setup.
The borrowing rules
At any time you can have either any number of shared references or exactly one mutable reference, and references must always be valid. The compiler (the "borrow checker") enforces this, which is how Rust prevents data races and dangling pointers.
fn main() {
let mut stock = vec![3, 1, 4];
let first = &stock[0]; // shared borrow
println!("first item: {first}");
// stock.push(9); // error while `first` is still used later
stock.push(9); // fine: `first` is no longer used
let biggest = stock.iter().max().unwrap();
println!("biggest: {biggest}, all: {stock:?}");
}
Output
first item: 3 biggest: 9, all: [3, 1, 4, 9]
Run this on your computer — see “Get Started” for setup.
Test yourself
Which is allowed at the same time?
Many mutable referencesMany shared references, or one mutable referenceOne shared and one mutable referenceAnything, if you're careful
Show answer
Answer: Many shared references, or one mutable reference