References & Borrowing Rules
Passing ownership to functions can be inconvenient. Rust provides references to let you access values without taking ownership. This is called borrowing.
1 References Borrowing Rules (Aliasing & Mutation)
Borrowing references (`&T`) must follow strict compiler safety rules:
- You can have any number of immutable references (`&T`) to a resource.
- You can have **only one** mutable reference (`&mut T`) to a resource at a time.
- You cannot have a mutable reference if immutable references already exist.
These rules prevent data races at compile time, guaranteeing thread safety.
2 Borrowing Code
Let's run a program illustrating borrowing rules and reference modifiers:
Rust — Borrowing
▶ Run Code
fn main() {
let mut s1 = String::from("hello");
// Borrowing immutably
let r1 = &s1;
let r2 = &s1;
println!("Immutables: {} and {}", r1, r2);
// r1 and r2 scopes end here
// Borrowing mutably
let r3 = &mut s1;
r3.push_str(", world");
println!("Mutable update: {}", r3);
}
3 Code Challenge
Challenge: Write a function that accepts an immutable reference to a string and prints its length. Write another function that accepts a mutable reference to a string and appends your name. Test both.