skip to content

References and Aliasing

Rust allows many shared &T borrows or one exclusive &mut T, never both, which rules out data races and iterator invalidation. Interviewers ask why the rule exists.

on this pageshow

questions

5

Why can a Rust reference never be null or dangling, and how do you return a lookup that may find nothing?

level: juniorimportance: must knowfreq 60%

answer

  1. no null literal for references
  2. does not live long enough
  3. absence lives in the type
  4. Option<&T> costs nothing extra

basics

~20 s

Safe Rust has no way to write a null reference, and rustc rejects any borrow used after its referent is dropped (E0597). A lookup that may find nothing returns Option<&T>, which std guarantees is the same size as &T.

solid answer

~50 s

A `&T` or `&mut T` must always point at a live, valid value; the Reference lists a null, dangling or misaligned reference as undefined behaviour, and safe code gives you no way to make one. There is no null literal for references, and the borrow checker proves every reference is used only while its referent is alive: borrowing a local inside a block and reading it after the block ends fails with E0597, '`inv.stock` does not live long enough'. Absence is expressed in the type instead: `fn stock_of(&self, slot: usize) -> Option<&u32>` makes the caller handle `None`, often via `Vec::get`. The `Option` costs nothing, because std guarantees `Option<&T>` has the same size as `&T`, using the forbidden null value to mean `None`. Raw pointers such as `*const T` can be null, and dereferencing them is `unsafe`.

code

rust · 21 lines
rust
use std::mem::size_of;

struct Inventory {
    stock: Vec<u32>,
}

impl Inventory {
    // No null: absence is a value the caller must handle.
    fn stock_of(&self, slot: usize) -> Option<&u32> {
        self.stock.get(slot)
    }
}

fn main() {
    let inv = Inventory { stock: vec![3, 5] };
    match inv.stock_of(7) {
        Some(qty) => println!("slot 7 holds {qty}"),
        None => println!("slot 7 is empty"),
    }
    println!("{}", size_of::<Option<&u32>>() == size_of::<&u32>());
}

go deeper

for a junior

Recall that references are never null or dangling, that absence is written as Option<&T>, and that a borrow of a local cannot be used after its block ends.

for a middle

Explain how the borrow checker proves no reference outlives its referent, citing E0597 and E0505, and why returning a reference to a local is impossible.

for a senior

Explain the validity invariant: a null or dangling reference is undefined behaviour, which is why rustc can tell LLVM references are dereferenceable and why Option<&T> needs no extra space.

for a principal

Use the guarantee in API review: a function returning Option<&T> or Result states its failure modes in the type, so a team can reject sentinel values and panicking lookups in shared crates.

## Two guarantees every reference carries A Rust reference, `&T` or `&mut T`, promises two things that a raw pointer does not: - **It is never null.** There is no null literal for references in safe Rust, and no safe operation produces one. - **It never dangles.** A reference is only ever used while the value it points to is alive. The Rust Reference makes these part of a reference's **validity invariant**: a reference must be aligned and non-null, cannot be dangling, and must point to a valid value. Producing one that breaks this is **undefined behaviour**, so the compiler is allowed to rely on it. You can see rustc doing so: compiling a function that takes a `&u32` and a `&mut u32` at `-C opt-level=3` and reading the LLVM IR shows both parameters marked `dereferenceable`, a promise to the optimiser that each points at real memory. ## How rustc prevents dangling references The borrow checker tracks how long each value lives and where each borrow is used. A borrow that would be used after its referent is gone is rejected at compile time: ```rust let first; { let inv = Inventory { stock: vec![3, 5] }; first = &inv.stock[0]; } // inv is dropped here println!("{first}"); ``` rustc reports E0597, '`inv.stock` does not live long enough', pointing at the drop at the closing brace and the later use in `println!`. Related cases are rejected the same way: 1. **Moving the owner while it is borrowed.** `let moved = inv;` while `first` is still going to be used fails (E0505), since the move could free or relocate the value. 2. **Returning a reference to a local.** `fn load() -> &Inventory` that returns `&inv` for a local `inv` fails at the signature: with no input reference, rustc cannot give the returned reference a lifetime and reports E0106, missing lifetime specifier, suggesting an owned `Inventory` instead. How lifetime annotations work is the subject of the lifetimes material. 3. **Mutating a container while a reference into it is live.** A `push` that might reallocate is rejected under the aliasing rule, which is the other half of "never dangling". ## Expressing "nothing found" without null Since a reference cannot be null, absence has to be written into the type. The standard tool is `Option<&T>`: ```rust fn stock_of(&self, slot: usize) -> Option<&u32> { self.stock.get(slot) } ``` The caller must handle both `Some(qty)` and `None`, through `match`, `if let`, or combinators such as `map` and `unwrap_or`. The compiler will not let it forget the `None` case. Common ways to consume it: - `if let Some(qty) = inv.stock_of(2) { .. }` when only the found case matters; - `inv.stock_of(2).copied()` to turn an `Option<&u32>` into an `Option<u32>` once the borrow is no longer wanted; - `inv.stock_of(2).map(|qty| *qty * 2).unwrap_or(0)` to compute a fallback in one expression; - `?` inside a function that itself returns `Option`, to pass the `None` upward. ## It costs nothing: the null pointer optimisation You might expect `Option<&u32>` to need an extra tag. It does not. The `std::option` documentation **guarantees** that for `&U`, `&mut U`, `Box<U>`, `NonNull<U>`, the `NonZero` integers and function pointers, `Option<T>` has the same size, alignment and call ABI as `T`. Since a valid reference is never the all-zero value, that bit pattern is free to mean `None`. This is called the **null pointer optimisation**; the general idea of using impossible values as tags belongs to the material on enums and niches. In the example below, `size_of::<Option<&u32>>() == size_of::<&u32>()` prints `true`. ## References versus raw pointers | Property | `&T` / `&mut T` | `*const T` / `*mut T` | |---|---|---| | Can be null | no | yes, for example `std::ptr::null()` | | Can dangle | no, checked at compile time | yes, nothing checks it | | Dereferencing | safe | requires `unsafe` | | Optional form | `Option<&T>`, same size | null itself, or `Option<NonNull<T>>` | Raw pointers exist for foreign-function interfaces and low-level data structures; the rules for using them soundly are covered with unsafe Rust. ## Why interviewers ask - It checks that the candidate knows **where** the guarantee comes from: a compile-time check plus a validity invariant, not a runtime null check. - It checks that they reach for **`Option<&T>`** rather than a sentinel value or a panic when something may be missing. - It is a natural lead-in to lifetimes, since E0106 and E0597 are where most people first meet them.

  • Why does `fn load() -> &Inventory` that returns a reference to a local fail with E0106 rather than E0597?
    The signature has no input reference, so lifetime elision has nothing to tie the returned reference to, and rustc stops at the signature with E0106, missing lifetime specifier. Its help suggests returning an owned `Inventory`, which is the right fix: the local is dropped at the end of the function, so no borrow of it can be returned.
  • Does `Option<&T>` take more memory than `&T`?
    No. The `std::option` docs guarantee that `Option<&U>` has the same size, alignment and call ABI as `&U`, because a reference is never null and the null value can encode `None`. The same holds for `Box<U>`, `&mut U` and `NonNull<U>`.

  • Rust checks references for null at run time before each dereference.
  • Option<&T> doubles the size of a reference because of the tag.
  • Returning &local works if the caller uses the result immediately.
  • Indexing a Vec out of range hands back a null reference instead of panicking.
open as a page

In Rust, what is the difference between `&T` and `&mut T`, and why can both never be in use for the same value at once?

level: juniorimportance: must knowfreq 82%

basics

~20 s

A &T is a shared, read-only borrow, and many can coexist; a &mut T is an exclusive borrow that permits mutation, so while it is in use no other path to the value may be used. rustc checks this at compile time.

open as a page

When rustc resolves `inv.total()`, how do auto-referencing and auto-dereferencing make it work for `Inventory`, `&Inventory` and `Box<Inventory>` receivers?

level: middleimportance: should knowfreq 42%

basics

~20 s

For a method call, rustc builds candidate receiver types by repeatedly dereferencing the receiver, adding &T and &mut T after each, and picks the first that has a matching method. So inv.total() becomes Inventory::total(&inv) whatever pointer inv is.

open as a page

In Rust, how can a function pass its `&mut Inventory` parameter to two calls in a row when `&mut T` is not `Copy`?

level: middleimportance: should knowfreq 40%

basics

~20 s

Each call reborrows: where the parameter type is known to be &mut Inventory, the compiler passes a fresh &mut *inv for the call instead of moving inv, so inv is usable afterwards. A generic T parameter moves it instead.

open as a page

Why does Rust forbid a `&mut T` alongside any other reference to the same value even in single-threaded code, and what does that guarantee buy?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Mutation through one path invalidates what another path assumes: a Vec push can reallocate under a live iterator, and a write can change a value a caller just read. Exclusive &mut rules that out and lets rustc optimise assuming no overlap.

open as a page