skip to content

Smart Pointers

Box, Rc, Weak, Cell, RefCell, Cow and the once-cells bend single ownership where a design needs it. Interviewers ask what each costs and which runtime checks it moves the rules into.

on this pageshow

explore

questions

24

In Rust, why does `enum Expr { Num(i64), Add(Expr, Expr) }` fail with E0072, and how does `Box` fix it?

level: juniorimportance: must knowfreq 75%

answer

  1. size known at compile time
  2. a variant contains itself
  3. indirection breaks the cycle
  4. a pointer has a fixed size

basics

~20 s

rustc needs every type's size at compile time, and an Expr holding two Exprs inline would be infinitely large. Boxing each child puts it on the heap behind a fixed-size pointer, so Expr gets a finite size.

solid answer

~40 s

An enum must hold its largest variant inline, so `Add(Expr, Expr)` would have to contain two whole `Expr` values, each containing two more, with no finite size. rustc rejects it with E0072, "recursive type `Expr` has infinite size". A `Box<Expr>` is a single pointer to a heap allocation, so `Add(Box<Expr>, Box<Expr>)` has a fixed size (24 bytes on a 64-bit target) however deep the tree grows. Every recursive field needs its own indirection: rustc's help boxes only the first field, and fixing that alone surfaces E0072 on the second. `Vec<Expr>`, `Rc<Expr>` or `&'a Expr` also break the cycle; `Option<Expr>` does not, because `Option` stores its payload inline.

code

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

enum Expr {
    Num(i64),
    Neg(Box<Expr>),
    Add(Box<Expr>, Box<Expr>),
    Mul(Box<Expr>, Box<Expr>),
}

fn eval(e: &Expr) -> i64 {
    match e {
        Expr::Num(n) => *n,
        Expr::Neg(inner) => -eval(inner),
        Expr::Add(a, b) => eval(a) + eval(b),
        Expr::Mul(a, b) => eval(a) * eval(b),
    }
}

fn main() {
    // (2 + 3) * -4
    let e = Expr::Mul(
        Box::new(Expr::Add(Box::new(Expr::Num(2)), Box::new(Expr::Num(3)))),
        Box::new(Expr::Neg(Box::new(Expr::Num(4)))),
    );
    println!("value = {}", eval(&e));
    println!("size_of::<Expr>() = {}", size_of::<Expr>());
    println!("size_of::<Box<Expr>>() = {}", size_of::<Box<Expr>>());
    println!("size_of::<Option<Box<Expr>>>() = {}", size_of::<Option<Box<Expr>>>());
}

go deeper

for a junior

Recall the rule: every type needs a size known at compile time, and a type that contains itself inline has none. Box the recursive field and name E0072.

for a middle

Explain the layout: an enum holds its largest variant inline, a Box is one pointer, and every recursive field needs its own indirection, which is why Vec or Rc also work and Option alone does not.

for a senior

Show you know the costs: one allocation per node, recursive drop that can overflow the stack on very deep chains, and when Vec children or an arena of indices beat a Box per node.

for a principal

Weigh a Box-per-node tree against an arena with integer indices for a large AST: allocation count, cache locality and how lifetimes or indices change every pass that walks the tree.

## Why rustc needs a size for every type In Rust, every type that lives directly in a variable, a struct field or an enum variant must have a **size known at compile time** (the `Sized` property). rustc uses that size to lay out stack frames, to compute field offsets and to decide how many bytes a move copies. An enum is laid out as roughly **its largest variant plus a tag** (the discriminant) that records which variant is active. Now take an expression-tree interpreter: ```rust enum Expr { Num(i64), Add(Expr, Expr), } ``` To size `Expr`, rustc must size `Add`, which contains two whole `Expr` values stored inline, each of which may be an `Add` containing two more, and so on. The equation `size(Expr) = tag + 2 * size(Expr)` has no finite solution, so the compiler refuses the definition. ## What E0072 says rustc 1.99 reports it like this: ```plaintext error[E0072]: recursive type `Expr` has infinite size --> a1.rs:1:1 | 1 | enum Expr { | ^^^^^^^^^ 2 | Num(i64), 3 | Add(Expr, Expr), | ---- recursive without indirection | help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle ``` The error-code index puts it plainly: any use of the type being defined from inside its own definition must occur **behind a pointer**, because structs and enums need a well-defined size. ## How `Box` fixes it `Box<T>` is an owning pointer to one value of `T` on the heap. For a sized `T`, std guarantees a `Box<T>` is represented as **a single pointer**, so its size does not depend on what it points to. ```rust enum Expr { Num(i64), Neg(Box<Expr>), Add(Box<Expr>, Box<Expr>), Mul(Box<Expr>, Box<Expr>), } ``` On a 64-bit target this `Expr` is 24 bytes: two 8-byte pointers for the widest variant plus the tag, rounded to alignment. Each child lives in its own heap allocation, and the tree's depth no longer affects `size_of::<Expr>()`. | Field type for a child | Stored | Compiles? | |---|---|---| | `Expr` | inline | no, E0072 | | `Option<Expr>` | inline | no, E0072 | | `[Expr; 1]` | inline | no, E0072 | | `Box<Expr>` | heap, one pointer | yes | | `Vec<Expr>` | heap buffer, 3-word handle | yes | | `Rc<Expr>` | shared heap value, one pointer | yes | | `&'a Expr` | borrowed, one pointer | yes | ## Every recursive occurrence needs indirection A common slip is boxing only one field. rustc's help for `Add(Expr, Expr)` suggests `Add(Box<Expr>, Expr)`, and applying only that produces E0072 again, now pointing at the second field. Every path from `Expr` back to `Expr` must pass through a pointer: - **each field** of each variant that holds an `Expr` needs its own indirection; - **nested wrappers** count only if one of them is a pointer: `Option<Box<Expr>>` works, `Box<Option<Expr>>` also works, `Option<Expr>` does not; - **mutual recursion** (a `Stmt` holding an `Expr` that holds a `Stmt`) needs a pointer somewhere on the cycle, not necessarily in both types. ## Choosing the indirection `Box` is the default because it keeps **single ownership**: dropping the root drops the whole tree, with no counts and no lifetimes. The alternatives each solve a different problem: 1. `Vec<Expr>` when a node has a variable number of children, such as a function call's arguments; the vector is already a heap handle, so boxing its elements only adds allocations. 2. `Rc<Expr>` when subtrees are shared between several parents. 3. `&'a Expr` when the nodes live in an arena or a parsed buffer that outlives the tree. ## Working with a boxed tree Code that walks the tree barely notices the boxes: `match` on `&Expr`, and deref coercion lets `eval(inner)` accept a `&Box<Expr>` where `&Expr` is expected. When you consume a tree, `*boxed` moves the value out of its box, which `Box` alone among std's smart pointers allows. Two costs remain: one allocation per node, and **recursive drop**. Dropping a very deep chain, such as a million nested `Neg` nodes, recurses once per level and can overflow the stack, so very deep lists and trees often get a hand-written iterative `Drop`.

  • Why does `Sum(Vec<Expr>)` compile without any `Box`?
    A `Vec<Expr>` is itself a fixed-size handle (pointer, capacity and length, 24 bytes on a 64-bit target) to a heap buffer, so it already supplies the indirection. Writing `Vec<Box<Expr>>` instead adds one more allocation per child and gains nothing for the layout.
  • How large is `Option<Box<Expr>>`, and why?
    The same as `Box<Expr>`: 8 bytes on a 64-bit target. A `Box` is never null, and std guarantees that `Option<Box<U>>` for a sized `U` has the same size as the box, with `None` using the null value. A linked list's `Option<Box<Node>>` tail therefore costs no extra tag.
  • When you consume a tree, how do you get the child out of `Neg(Box<Expr>)` by value?
    Match the node by value and dereference the box: `Expr::Neg(inner) => *inner` moves the `Expr` out and frees the box's allocation. `Box` is the only std smart pointer that allows moving out through `*`; the same move out of an `Rc` fails with E0507.

A form that must include a complete copy of itself can never be printed; a form that writes a filing number pointing to another form fits on one page however long the chain of forms gets.

  • Recursive types need Box because the heap has more room than the stack.
  • One Box anywhere in a variant is enough to break the recursion.
  • Option<Expr> works because None carries no data.
  • E0072 is a borrow-checker error about a value owning itself.
  • Only Box can break the cycle; Vec or a reference never can.
open as a page

In Rust, when do you use `Cell<T>` rather than `RefCell<T>` for state that a `&self` method must change?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Cell<T> fits small values replaced whole, like a hit counter: it moves values in and out and never lends a reference. RefCell<T> lends &T or &mut T through guards, for a map or Vec, checking borrows at run time and panicking on conflict.

open as a page

In Rust, what does `Rc::clone(&config)` do to an `Rc<String>`, and when is the `String` itself dropped?

level: juniorimportance: must knowfreq 74%

basics

~20 s

Rc::clone copies no String data: it adds one to the strong count and returns another pointer to the same heap allocation. Each Rc dropped subtracts one, and the String is dropped when the last strong Rc goes away.

open as a page

In Rust, why model shared bank accounts as `Rc<RefCell<Account>>`, and what does each of the two layers contribute?

level: middleimportance: must knowfreq 70%

basics

~20 s

Rc<T> gives one value several owners but only lends &T, so assigning through it fails with E0594. RefCell<T> adds mutation through that &T, checked at run time. Together they give many handles, each able to borrow_mut the account, on one thread.

open as a page

With Rust's `RefCell`, why does a method that calls `borrow_mut()` while iterating over `borrow()` compile, yet panic at run time?

level: middleimportance: must knowfreq 74%

basics

~20 s

RefCell moves the borrow rules to run time. The Ref from borrow() stays alive for the whole for loop, so borrow_mut() inside it finds a live shared borrow and panics with "RefCell already borrowed". Shorten the shared borrow, or use try_borrow_mut.

open as a page

In current Rust, how do you declare a global value built on first use, such as a table of compiled regexes, without the `lazy_static!` macro?

level: middleimportance: must knowfreq 55%

basics

~20 s

Declare static RULES: LazyLock<T> = LazyLock::new(|| ...) using std::sync::LazyLock, stable since Rust 1.80. The closure runs once, on the first dereference by whichever thread arrives first, and every later access gets a shared reference to the stored value.

open as a page

In Rust, building a DOM-like tree of `Rc` nodes with parent links, why must the parent field be a `Weak`, and what does `Weak::upgrade` return?

level: middleimportance: must knowfreq 66%

basics

~20 s

Children are owned through Rc and point back through std::rc::Weak, because a strong parent link forms a cycle whose counts never reach zero, so nothing is dropped. Weak::upgrade returns Some(Rc) while the parent lives and None afterwards.

open as a page

In Rust, what does a `std::borrow::Cow<'a, str>` hold, and how do you read its text or turn it into a `String`?

level: juniorimportance: should knowfreq 35%

basics

~10 s

A Cow<'a, str> is an enum holding either Cow::Borrowed(&'a str) or Cow::Owned(String). It derefs to str, so you read it like a &str, and into_owned() returns a String, allocating only when it was borrowed.

open as a page

In Rust, how does `std::cell::OnceCell` let you fill a value once through a shared reference, and what do `get`, `set` and `get_or_init` return?

level: juniorimportance: should knowfreq 40%

basics

~20 s

OnceCell<T>, stable since Rust 1.70, starts empty and can be written exactly once through &self. get returns Option<&T>, get_or_init runs its closure only while the cell is empty and returns &T, and set returns Err(value) if a value is already stored.

open as a page

In Rust, when would you store a `Box<[T]>` or `Box<str>` instead of a `Vec<T>` or `String`, and what do you give up?

level: middleimportance: should knowfreq 30%

basics

~20 s

Use Box<[T]> or Box<str> for data that is finished and will never grow: the handle is two words instead of three and into_boxed_slice trims spare capacity. You lose push, insert and every other length-changing method.

open as a page

When should a Rust function return `Cow<'a, str>` instead of `String`, for example a sanitiser that rarely needs to escape anything?

level: middleimportance: should knowfreq 35%

basics

~20 s

Return Cow<'a, str> when a function takes a &str and usually returns it unchanged: the common path returns Cow::Borrowed(input) with no allocation, and only the rare path that changes the text builds a String and returns Cow::Owned.

open as a page

In Rust, what does `Cow::to_mut` do on a `Cow::Borrowed` versus a `Cow::Owned`, and how does it differ from `into_owned`?

level: middleimportance: should knowfreq 25%

basics

~20 s

Cow::to_mut takes &mut self and returns a mutable reference to the owned value: on Borrowed it clones the data once and switches the Cow to Owned, on Owned it clones nothing. into_owned consumes the Cow and returns the owned value, cloning only if Borrowed.

open as a page

In Rust, why does rustc reject a `static` of type `LazyCell` or `OnceCell` but accept `LazyLock` and `OnceLock`, and when is each pair the right choice?

level: middleimportance: should knowfreq 30%

basics

~20 s

A shared static must be Sync. LazyCell and OnceCell are not, so rustc reports E0277; LazyLock and OnceLock synchronise the first write and are Sync for Send + Sync values. Use the Lock pair for globals and the Cell pair on one thread.

open as a page

Why does rustc reject moving even the only `Rc<Vec<i32>>` into `thread::spawn`, and what in `Rc` makes it neither `Send` nor `Sync`?

level: middleimportance: should knowfreq 55%

basics

~20 s

Rc keeps its strong and weak counts in plain Cell<usize> fields updated without atomics, so std declares Rc and Weak !Send and !Sync for every T. rustc checks the type, not the run-time count, so even a sole handle fails with E0277.

open as a page

A Rust debug build aborts with a stack overflow at `Box::new([0u8; 16 * 1024 * 1024])`; why, and how do you heap-allocate that buffer safely?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Box::new takes its argument by value, so the 16 MiB array is built on the stack and then copied to the heap, and an unoptimised build overflows the stack. Allocate on the heap directly with vec![0u8; N].try_into() or Box::new_zeroed().

open as a page

In Rust, when do you use `Box::leak` rather than `Box::into_raw`, and what must eventually happen to the pointer `into_raw` returns?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Box::leak gives up the allocation for good and returns a &'a mut T, often 'static, for data that lives until exit. Box::into_raw returns a *mut T, and its owner must later pass it to Box::from_raw exactly once to drop and free it.

open as a page

Why are Rust's `Cell` and `RefCell` not `Sync`, and what does `UnsafeCell`, the type both are built on, provide?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Cell and RefCell mutate through &T with plain, non-atomic operations, so two threads sharing one could race on the value or RefCell's borrow counter; std therefore marks them !Sync. Both wrap UnsafeCell, the only legal way to mutate data behind a shared reference.

open as a page

A Rust service loads its settings file from a path given on the command line; why can't a `static LazyLock` do this, and how does `OnceLock` handle it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

A static LazyLock's closure cannot capture main's local path, because a static initialiser is a constant context and rustc reports E0435. Declare static SETTINGS: OnceLock<Settings>, have main call set or get_or_init with the loaded value, and read it elsewhere with get.

open as a page

In Rust, when does `Rc::make_mut` clone the inner value, and how do `Rc::get_mut`, `Rc::try_unwrap` and `Rc::unwrap_or_clone` behave differently?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Rc::make_mut clones the value only when another strong Rc exists; with only Weak handles left it moves the value and those Weaks stop upgrading. Rc::get_mut never clones and returns None if shared; try_unwrap returns Err(rc) unless unique; unwrap_or_clone clones when shared.

open as a page

As a Rust lead, when do you accept `Rc<RefCell<T>>` in a codebase, and when do you require restructuring ownership instead?

level: principalimportance: should knowfreq 34%

basics

~20 s

Accept Rc<RefCell<T>> for genuinely shared, single-threaded state contained behind a small API, such as UI callbacks updating one model. When it spreads through domain types, require a single owner with indices, explicit &mut passing or messages, which keep the checks at compile time.

open as a page

As a Rust lead, when do you allow a process-wide `LazyLock` or `OnceLock` global in a service, and when do you require passing state explicitly?

level: principalimportance: should knowfreq 32%

basics

~20 s

Allow a global when the value is immutable and self-contained, such as a table of compiled patterns or a process-wide facility set once at startup. Require explicit passing, usually an Arc<Config> field or a parameter, for anything tests vary, anything per tenant or request, and anything that holds mutable state.

open as a page

A Rust struct with a `Cow<'a, str>` field is deserialized with serde_json; why is the field always `Cow::Owned`, and when can it borrow instead?

level: seniorimportance: nice to knowfreq 25%

basics

~10 s

serde's Deserialize impl for Cow<'a, T> always deserializes T::Owned and wraps it in Cow::Owned. With #[serde(borrow)] on the field, serde_json::from_str yields Cow::Borrowed for strings without escapes and Cow::Owned when it must unescape.

open as a page

Why does `Cow<'_, [Token]>` fail with E0277 when `Token` is not `Clone`, and why do Rust APIs write `Cow<str>` rather than `Cow<String>`?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

Cow<'a, B> requires B: ToOwned, and std implements ToOwned for [T] only when T: Clone, so naming Cow<[Token]> fails with E0277 even if nothing is ever cloned. B is the borrowed form: str, whose owned type is String.

open as a page

In Rust, what happens to a `LazyLock` or an `OnceLock` when its initialiser panics, and what happens when an initialiser reenters the same cell?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

A panicking LazyLock or LazyCell initialiser poisons it, so every later access panics. A panicking OnceLock or OnceCell get_or_init leaves the cell empty, so the next call retries. Reentrant initialisation panics for OnceCell and currently deadlocks for OnceLock.

open as a page