Chapter 4: Borrowing & Lifetimes

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.

The Core Insight

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.

4.1 References: The Basics

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
References vs Ownership

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.

The Ampersand (&) Operator

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)

4.2 Immutable References

By default, references are immutable. You can read the data but not modify it:

Immutable Reference (&T)

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
}

Why Multiple Immutable References Are Safe

Multiple readers don't conflict. If no one is modifying the data, any number of functions can read it simultaneously without risk of inconsistency.

4.3 Mutable References

To modify borrowed data, you need a mutable reference with &mut:

Mutable Reference (&mut T)

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
}
The Variable Must Be Mutable

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.

4.4 The Borrowing Rules

Rust enforces two critical rules to prevent data races at compile time:

Rule 1: One Mutable OR Many Immutable

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);
Why This Rule Exists

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.

Rule 2: References Must Be Valid

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
}

4.5 Non-Lexical Lifetimes (NLL)

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 Compiler Is Smart

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.

4.6 Lifetime Annotations

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."

Reading Lifetime Syntax

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

Lifetime Elision Rules

In many cases, Rust infers lifetimes automatically using these rules:

  1. Each input reference gets its own lifetime parameter
  2. If there's exactly one input lifetime, it's assigned to all output references
  3. If one of the inputs is &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 { ... }

4.7 The 'static Lifetime

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
Be Careful with 'static

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.

4.8 Chapter Summary

Key Takeaways

4.9 Review Questions

Test Your Understanding

  1. What's the difference between ownership and borrowing?
  2. Explain the two borrowing rules. Why does Rust enforce them?
  3. What's the difference between &String and &mut String?
  4. What is a lifetime? When do you need to annotate them explicitly?
  5. What are the lifetime elision rules? Give an example where they apply.
  6. What does 'static mean? Give an example of data with a static lifetime.

4.10 Looking Ahead

What's Next: Chapter 5 - Structuring Your Code

With ownership and borrowing mastered, you're ready to build larger programs: