Borrowing & Lifetimes

References without taking ownership — shared and mutable borrows, the aliasing XOR mutability rule, the borrow checker and non-lexical lifetimes, dangling references, slices, lifetime annotations and elision, and 'static.

Intermediate 3 min readLesson 3 of 9 Interview Q&A

Moving ownership into every function would be impractical. Instead, Rust lets you borrow: create a reference to a value without taking ownership. The borrow checker proves at compile time that every reference is valid and that data is never mutated while someone else is reading it.

References

Rust
fn length(s: &String) -> usize {     // borrow: s is a reference, not the owner
    s.len()
}                                    // nothing is dropped — we never owned it

let text = String::from("hello");
let n = length(&text);               // & creates a reference
println!("{text} has {n} bytes");    // ✓ text still owned here

Mutable references

Rust
fn shout(s: &mut String) {
    s.push_str("!");
}

let mut text = String::from("hello");
shout(&mut text);                    // explicit &mut at the call site

The borrowing rules

At any given time, for a particular value, you may have either:

  • any number of shared references (&T), or
  • exactly one mutable reference (&mut T),

but not both. And references must always be valid (never outlive the data).

This is "aliasing XOR mutability": data can be shared or mutated, never both at once.

Rust
let mut v = vec![1, 2, 3];
let first = &v[0];          // shared borrow
v.push(4);                  // ✗ error: cannot borrow `v` as mutable because it is also borrowed as immutable
println!("{first}");

That error prevents a real bug: push may reallocate the vector's buffer, leaving first pointing at freed memory. In C++ this compiles and corrupts memory; in Rust it doesn't compile.

The same rule prevents iterator invalidation and, across threads, data races (a data race needs two accesses, at least one a write, without synchronisation — impossible if mutation requires exclusive access).

Non-lexical lifetimes

A borrow lasts until the reference's last use, not until the end of the block:

Rust
let mut s = String::from("hi");
let r1 = &s;
let r2 = &s;
println!("{r1} {r2}");      // last use of r1 and r2
let r3 = &mut s;            // ✓ fine: the shared borrows have ended
r3.push('!');

No dangling references

Rust
fn dangle() -> &String {           // ✗ error: missing lifetime specifier
    let s = String::from("hello");
    &s                             // s is dropped at the end of the function
}

fn no_dangle() -> String {         // ✓ return the owned value instead
    String::from("hello")
}

Slices

A slice is a reference to a contiguous part of a collection: a pointer plus a length.

Rust
let s = String::from("hello world");
let hello: &str = &s[0..5];
let world: &str = &s[6..];

let nums = [1, 2, 3, 4, 5];
let middle: &[i32] = &nums[1..4];      // [2, 3, 4]

fn first_word(s: &str) -> &str {       // returns a slice borrowing from the input
    s.split(' ').next().unwrap_or("")
}

let mut text = String::from("hello world");
let word = first_word(&text);
text.clear();                          // ✗ can't mutate while `word` borrows from text
println!("{word}");

Take &str and &[T] in parameters rather than &String and &Vec<T> — they accept more inputs.

Lifetimes

A lifetime is the region of code during which a reference is valid. The compiler infers most of them. You annotate them only when a function returns a reference and the compiler can't tell which input it borrows from:

Rust
fn longest(a: &str, b: &str) -> &str {     // ✗ which input does the result borrow from?
    if a.len() > b.len() { a } else { b }
}

fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {   // ✓
    if a.len() > b.len() { a } else { b }
}

'a is a generic lifetime parameter. The signature says: "the returned reference is valid for as long as both inputs are" (the shorter of the two). Annotations don't change how long anything lives — they describe relationships so the compiler can check callers:

Rust
let outer = String::from("long string");
let result;
{
    let inner = String::from("xyz");
    result = longest(&outer, &inner);
}                                     // inner dropped here
println!("{result}");                 // ✗ `inner` does not live long enough

Lifetime elision

You rarely write lifetimes because of three elision rules:

  1. Each reference parameter gets its own lifetime.
  2. If there's exactly one input lifetime, it's assigned to all output references.
  3. If there's a &self or &mut self parameter, its lifetime is assigned to all outputs.

So fn first_word(s: &str) -> &str and fn name(&self) -> &str need no annotations.

Structs holding references

Rust
struct Excerpt<'a> {
    part: &'a str,           // an Excerpt can't outlive the text it borrows
}

let novel = String::from("Call me Ishmael. Some years ago...");
let first = novel.split('.').next().unwrap();
let e = Excerpt { part: first };

Owning data (String) in structs is simpler; borrowing (&'a str) avoids copies for short-lived views (parsers, iterators).

'static

'static means "valid for the entire program". String literals are &'static str (baked into the binary). As a bound (T: 'static) it means the type contains no non-static references — e.g. data moved into a spawned thread must be 'static because the thread might outlive the caller.

Key takeaways
  • & borrows a value without owning it; &mut borrows it exclusively for mutation.
  • Many shared borrows or one mutable borrow — never both (aliasing XOR mutability).
  • This rule prevents dangling pointers, iterator invalidation and data races at compile time.
  • Borrows end at their last use (non-lexical lifetimes).
  • Lifetime annotations relate input and output references; elision rules cover most functions.
  • Prefer &str and &[T] in parameters; 'static means valid for the whole program.
Interview questions
QWhat are Rust's borrowing rules and what bugs do they prevent?medium

At any time a value may have either any number of immutable references or exactly one mutable reference, and references must never outlive the value. This prevents use-after-free and dangling pointers, iterator invalidation (mutating a collection while referencing its elements), and data races, since concurrent mutation would require multiple mutable references.