What if you want to use a value without taking ownership? That's where borrowing comes in. Borrowing lets you reference data without owning it, enabling more flexible and efficient code while maintaining Rust's safety guarantees.
References allow you to refer to a value without taking ownership. Like borrowing a book from a library—you can read it, but you don't own it, and you must return it.
A reference is like a pointer that's guaranteed to point to valid data. You create a reference using the & operator:
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1); // Pass a reference, not ownership
println!("The length of '{}' is {}.", s1, len); // s1 is still valid!
}
fn calculate_length(s: &String) -> usize { // s is a reference to a String
s.len()
} // s goes out of scope, but it doesn't own the data, so nothing is dropped
When you pass &s1, you're passing a reference. The function borrows the data but doesn't own it. When the function ends, the borrow ends, but the original data remains with the owner.
| Syntax | Meaning |
|---|---|
&value |
Create an immutable reference to value |
&mut value |
Create a mutable reference to value |
*reference |
Dereference (follow the reference to the value) |
By default, references are immutable. You can read the data but not modify it:
An immutable reference lets you read data without modifying it. Think of it as "read-only access." You can have multiple immutable references to the same data.
fn main() {
let s = String::from("hello");
let r1 = &s; // OK
let r2 = &s; // OK - multiple immutable refs allowed
println!("{} and {}", r1, r2); // Both work
}
Multiple readers don't conflict. If no one is modifying the data, any number of functions can read it simultaneously without risk of inconsistency.
To modify borrowed data, you need a mutable reference with &mut:
A mutable reference lets you read AND modify the data. But there's a restriction: you can only have one mutable reference to a value at a time.
fn main() {
let mut s = String::from("hello"); // s must be declared mut
change(&mut s); // Pass a mutable reference
println!("{}", s); // Prints "hello, world"
}
fn change(some_string: &mut String) {
some_string.push_str(", world"); // Modify the borrowed data
}
To create a mutable reference, the original variable must be declared with let mut. You can't get a mutable reference to an immutable binding.
Rust enforces two critical rules to prevent data races at compile time:
At any given time, you can have either:
But NOT both at the same time!
// This is OK: multiple immutable references
let s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{} and {}", r1, r2);
// This is NOT OK: mutable reference while immutable exists
let mut s = String::from("hello");
let r1 = &s; // immutable borrow
let r2 = &mut s; // ERROR! Can't borrow as mutable while immutable ref exists
println!("{}", r1);
This rule prevents data races at compile time. A data race occurs when:
Rust eliminates this entire class of bugs by enforcing exclusive access for mutation.
A reference cannot outlive the data it refers to. No dangling references!
// This won't compile - dangling reference
fn dangle() -> &String {
let s = String::from("hello");
&s // ERROR! s is dropped when function ends, but we're returning a ref
}
// This is correct - return ownership instead
fn no_dangle() -> String {
let s = String::from("hello");
s // Ownership is moved out, no dangling reference
}
Modern Rust uses "Non-Lexical Lifetimes" - references end when they're last used, not when they go out of scope:
let mut s = String::from("hello");
let r1 = &s; // immutable borrow starts
let r2 = &s; // another immutable borrow
println!("{} and {}", r1, r2); // r1 and r2 are last used here
// After this point, r1 and r2 are no longer in use
let r3 = &mut s; // OK! mutable borrow starts here
println!("{}", r3);
The Rust compiler tracks exactly where each reference is used. References are considered "live" only until their last use, not until the end of the scope. This makes Rust more ergonomic without sacrificing safety.
Sometimes the compiler needs help understanding how long references should live. That's where lifetime annotations come in:
// 'a is a lifetime parameter
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
The 'a annotation means: "the returned reference will live at least as long as the shorter of the two input references."
| Syntax | Meaning |
|---|---|
&'a T |
Reference to T with lifetime 'a |
&'a mut T |
Mutable reference to T with lifetime 'a |
fn foo<'a>(x: &'a str) |
Function with lifetime parameter |
struct Foo<'a> { x: &'a str } |
Struct holding a reference |
In many cases, Rust infers lifetimes automatically using these rules:
&self or &mut self, its lifetime is assigned to outputs// These two signatures are equivalent:
fn first_word(s: &str) -> &str { ... }
fn first_word<'a>(s: &'a str) -> &'a str { ... }
The special 'static lifetime means the reference lives for the entire program:
let s: &'static str = "I have a static lifetime."; // String literals are stored in the program binary and always valid
Don't overuse 'static. Usually when the compiler suggests it, there's a better solution. String literals are naturally 'static, but most data isn't.
& to borrow data without taking ownership&T allows reading; multiple immutable refs allowed&mut T allows modification; only one at a time'a tell the compiler how long refs should live&String and &mut String?'static mean? Give an example of data with a static lifetime.With ownership and borrowing mastered, you're ready to build larger programs: