Sub topic 1
Rust Borrowing and References: Sharing Data Without Giving Up Ownership
Prerequisites
Assume you know basic Rust syntax, String, Vec, &str, and how to build and run a Cargo program. You should also understand that heap data has one owner.
Why borrowing exists: ownership and moves
Rust gives each value one owner. Assigning a value to another variable usually moves ownership:
fn main() {
let name = String::from("Ada");
let other = name;
println!("{other}");
// println!("{name}"); // error: name was moved
}After the move, name is no longer usable. This prevents two variables from freeing the same heap allocation. However, moving data every time a function uses it would be expensive or inconvenient. Borrowing lets code use a value temporarily without taking ownership.
Borrowing with shared references
A shared reference, written &T, provides read-only access. Creating one does not move the value.
fn length(s: &String) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let n = length(&s);
println!("{s} has length {n}");
}The function receives a reference to s, so main keeps ownership. In practice, accept &str when a function only needs text and can work with both String and string literals.
Changing borrowed data with `&mut`
A mutable reference, &mut T, allows in-place changes. Both the owner and the reference must be declared mutable.
fn add_suffix(s: &mut String) {
s.push('!');
}
fn main() {
let mut message = String::from("Hi");
add_suffix(&mut message);
println!("{message}");
}The function changes the original String; it does not create a replacement.
The borrowing rules: many readers or one writer
Rust enforces this rule:
- You may have many shared references, or
- You may have one mutable reference,
- but not both at the same time.
This prevents a writer from changing data while readers rely on an outdated layout. It also prevents data races in concurrent programs.
fn main() {
let mut values = vec![1, 2, 3];
let first = &values[0];
println!("{first}");
values.push(4);
println!("{values:?}");
}The shared borrow is no longer used when push needs a mutable borrow, so this program compiles.
Exercise
Why does fn take(s: String) prevent the caller from using its String, while fn take(s: &String) does not?
Show answer
The first parameter takes ownership by moving the String; the second only borrows it.