Read without taking over.
Let functions inspect values while the caller keeps ownership.
01 Understand the contract
A shared reference &T borrows a value without transferring ownership. Several shared references can coexist because safe Rust prevents conflicting ordinary mutation during those active borrows. A reference must not outlive its referent. Rust often ends a borrow after its last use, rather than waiting for the closing brace; this is why a later mutation can be allowed once earlier reads are finished. Prefer parameters such as &str or &[T] when a function only needs a view rather than ownership of a particular container.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn characters(text: &str) -> usize {
text.chars().count()
}
fn main() {
let name = String::from("Navan");
let size = characters(&name);
println!("{name}: {size} characters");
}Navan: 5 characters
- 1
&name borrows instead of moving the String.
- 2
The String reference can coerce to &str.
- 3
The caller still owns name after the function returns.
cargo run -p lesson_borrowing03 Mind the boundary
04 Your next build
Write a function accepting &[i32] and return the sum without consuming the collection.
Reveal one possible solution +
fn sum(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let values = vec![2, 4, 6];
assert_eq!(sum(&values), 12);
assert_eq!(values.len(), 3);
}05 Check your reasoning
Does passing &String transfer ownership of the String?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.