Course contentsShow
← Rust
Lesson 980 of 1,9109. Smart Pointers and Interior MutabilityFree lesson

Recursive Data Structures with Box

Solve the infinite size compilation error by wrapping recursive types in heap pointers.

In this lesson, you will learn how to overcome Rust’s "recursive type with infinite size" compilation error by using Box to introduce heap indirection.

The Recursive Sizing Problem

In Rust, the compiler must know the exact memory footprint of a type at compile time to allocate stack space. If you define a recursive structure like a linked list, you run into an issue:

struct List<T> {
    value: T,
    next: List<T>, // Error: infinite size!
}

Because a List contains another List, the compiler tries to calculate the size by nesting: size = size_of(T) + size_of(List). This results in a cycle that never terminates. Rust cannot allocate a stack frame for a structure that is infinitely large.

Solving with Heap Indirection

To break this cycle, we use Box<T>. A Box is a smart pointer that allocates its contents on the heap and keeps only a fixed-size pointer on the stack. Because a pointer has a known, constant size (usually 8 bytes on 64-bit systems), the compiler can finally resolve the size of the structure:

struct List<T> {
    value: T,
    next: Option<Box<List<T>>>,
}

Why this works

By wrapping List<T> in a Box, we transition the recursive component from being "inline" (stored directly in the struct) to being "pointed to" (stored on the heap). The List struct now only needs space for the value and a pointer. When you instantiate this list, the "nested" parts exist elsewhere in memory, allowing the stack to remain small and predictable.

Using Option is also necessary here; without it, the recursive chain would technically be infinite (you would need an initial List to create a List, leading to a "chicken and egg" initialization problem). Option provides a way to terminate the list by using None.

Key Takeaway: To define recursive types, use Box to move the recursive part onto the heap, transforming an infinitely sized structure into a fixed-size pointer reference.