---
title: "What is the purpose of Box<T> in Rust?"
description: "What Box<T> is for, what the extra indirection costs, and when a heap allocation is the right call rather than a reflex."
url: "https://mayorana.ch/en/blog/box-pointer-rust"
language: "en"
date: "2025-08-05"
author: "Mohamed Bennekrouf"
tags:
  - "rust"
  - "memory"
  - "box"
  - "heap"
  - "ownership"
fr_version: "https://mayorana.ch/fr/blog/box-pointer-rust-fr.md"
---

# What is the purpose of Box<T> in Rust?

`Box<T>` is a smart pointer in Rust that provides heap allocation for a value of type `T`. It is the simplest way to store data on the heap, offering ownership and memory safety guarantees without runtime overhead.

<div class="svg-container" style="margin:2rem 0;">
<svg class="mm7-fig" viewBox="0 0 800 240" width="100%" style="height:auto;max-width:780px;display:block;margin:0 auto;" role="img" aria-label="A Box pointer lives on the stack with a fixed size and uniquely owns a value allocated on the heap, compared against Rc and Arc which allow shared ownership">
<style>
.mm7-fig{--bg:#f8fafc;--box:#ffffff;--tx:#1e293b;--mut:#64748b;--ln:#cbd5e1;--ac:#FF6B00}
:root.dark .mm7-fig,[data-theme="dark"] .mm7-fig{--bg:#0f172a;--box:#1e293b;--tx:#f8fafc;--mut:#94a3b8;--ln:#475569}
.mm7-fig .box{fill:var(--box);stroke:var(--ln);stroke-width:1.5}
.mm7-fig .acbox{fill:var(--box);stroke:var(--ac);stroke-width:2}
.mm7-fig .title{font:700 13px ui-sans-serif,system-ui,sans-serif;fill:var(--tx)}
.mm7-fig .body{font:600 12px ui-sans-serif,system-ui,sans-serif;fill:var(--tx)}
.mm7-fig .cap{font:11px ui-sans-serif,system-ui,sans-serif;fill:var(--mut)}
.mm7-fig .ac{fill:var(--ac)}
.mm7-fig path{stroke:var(--ln);stroke-width:1.5;fill:none}
</style>
<defs>
<marker id="mm7-arrow" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 Z" style="fill:var(--ac)"/></marker>
</defs>
<!-- stack box -->
<rect x="60" y="40" width="180" height="70" rx="8" class="acbox"/>
<text x="150" y="68" text-anchor="middle" class="title ac">Box&lt;T&gt;</text>
<text x="150" y="86" text-anchor="middle" class="cap">stack: one pointer (usize)</text>
<!-- heap box -->
<rect x="400" y="40" width="200" height="70" rx="8" class="box"/>
<text x="500" y="68" text-anchor="middle" class="title">T value</text>
<text x="500" y="86" text-anchor="middle" class="cap">heap: uniquely owned</text>
<path d="M240,75 L400,75" style="stroke:var(--ac)" marker-end="url(#mm7-arrow)"/>
<!-- comparison row -->
<rect x="60" y="150" width="220" height="60" rx="8" class="acbox"/>
<text x="170" y="175" text-anchor="middle" class="body ac">Box&lt;T&gt;</text>
<text x="170" y="193" text-anchor="middle" class="cap">unique owner</text>
<rect x="300" y="150" width="220" height="60" rx="8" class="box"/>
<text x="410" y="175" text-anchor="middle" class="body">Rc&lt;T&gt;</text>
<text x="410" y="193" text-anchor="middle" class="cap">shared, single-thread refcount</text>
<rect x="540" y="150" width="220" height="60" rx="8" class="box"/>
<text x="650" y="175" text-anchor="middle" class="body">Arc&lt;T&gt;</text>
<text x="650" y="193" text-anchor="middle" class="cap">shared, atomic refcount</text>
</svg>
</div>

## What is Box<T>?

- **Heap Allocation**: Moves data from the stack to the heap.
  ```rust
  let x = Box::new(42); // `42` is stored on the heap
  ```
- **Ownership**: `Box<T>` owns the data and ensures it is dropped when the `Box` goes out of scope.
- **Fixed Size**: The `Box` itself is a pointer (`usize`) with a known stack size, even if `T` is dynamically sized (e.g., `Box<dyn Trait>`).

## When to Use Box<T>

### 1. Recursive Types (e.g., Linked Lists)
Rust requires compile-time-known sizes, but recursive types (like trees or lists) would be infinitely sized without indirection.

```rust
enum List {
    Cons(i32, Box<List>), // Without `Box`, this would be invalid
    Nil,
}
```

<div class="svg-container" style="margin:2rem 0;">
<svg class="mm7b-fig" viewBox="0 0 800 330" width="100%" style="height:auto;max-width:780px;display:block;margin:0 auto;" role="img" aria-label="Without Box each Cons variant embeds another whole List inline so its size never resolves, while with Box each node stores a fixed size pointer to the next node until Nil ends the chain">
<style>
.mm7b-fig{--bg:#f8fafc;--box:#ffffff;--tx:#1e293b;--mut:#64748b;--ln:#cbd5e1;--ac:#FF6B00}
:root.dark .mm7b-fig,[data-theme="dark"] .mm7b-fig{--bg:#0f172a;--box:#1e293b;--tx:#f8fafc;--mut:#94a3b8;--ln:#475569}
.mm7b-fig .box{fill:var(--box);stroke:var(--ln);stroke-width:1.5}
.mm7b-fig .acbox{fill:var(--box);stroke:var(--ac);stroke-width:2}
.mm7b-fig .deadbox{fill:none;stroke:var(--mut);stroke-width:1.5;stroke-dasharray:4 3}
.mm7b-fig .title{font:700 13px ui-sans-serif,system-ui,sans-serif;fill:var(--tx)}
.mm7b-fig .body{font:600 12px ui-sans-serif,system-ui,sans-serif;fill:var(--tx)}
.mm7b-fig .cap{font:11px ui-sans-serif,system-ui,sans-serif;fill:var(--mut)}
.mm7b-fig .ac{fill:var(--ac)}
.mm7b-fig .mut{fill:var(--mut)}
.mm7b-fig path{stroke:var(--ln);stroke-width:1.5;fill:none}
</style>
<defs>
<marker id="mm7b-arrow" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 Z" style="fill:var(--ln);stroke:none"/></marker>
<marker id="mm7b-arrowac" markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto"><path d="M0,0 L8,4 L0,8 Z" style="fill:var(--ac);stroke:none"/></marker>
</defs>
<!-- top row: without Box -->
<text x="30" y="30" class="title">Without Box: the size question never terminates</text>
<rect x="30" y="46" width="170" height="56" rx="8" class="box"/>
<text x="115" y="70" text-anchor="middle" class="body">Cons(i32, List)</text>
<text x="115" y="88" text-anchor="middle" class="cap">4 + size of List</text>
<rect x="240" y="46" width="170" height="56" rx="8" class="box"/>
<text x="325" y="70" text-anchor="middle" class="body">Cons(i32, List)</text>
<text x="325" y="88" text-anchor="middle" class="cap">4 + size of List</text>
<rect x="450" y="46" width="170" height="56" rx="8" class="box"/>
<text x="535" y="70" text-anchor="middle" class="body">Cons(i32, List)</text>
<text x="535" y="88" text-anchor="middle" class="cap">and so on, inline</text>
<rect x="660" y="46" width="110" height="56" rx="8" class="deadbox"/>
<text x="715" y="70" text-anchor="middle" class="body mut">size = infinite</text>
<text x="715" y="88" text-anchor="middle" class="cap">rustc rejects it</text>
<path d="M200,74 L240,74" marker-end="url(#mm7b-arrow)"/>
<path d="M410,74 L450,74" marker-end="url(#mm7b-arrow)"/>
<path d="M620,74 L660,74" marker-end="url(#mm7b-arrow)"/>
<text x="400" y="126" text-anchor="middle" class="cap">Each variant embeds a whole List by value, so the compiler cannot lay it out.</text>
<!-- bottom row: with Box -->
<text x="30" y="186" class="title ac">With Box: every node is a fixed 16 bytes</text>
<rect x="30" y="202" width="200" height="56" rx="8" class="acbox"/>
<text x="130" y="226" text-anchor="middle" class="body ac">Cons(i32, Box&lt;List&gt;)</text>
<text x="130" y="244" text-anchor="middle" class="cap">4 bytes + one 8-byte pointer</text>
<rect x="270" y="202" width="200" height="56" rx="8" class="box"/>
<text x="370" y="226" text-anchor="middle" class="body">next node on the heap</text>
<text x="370" y="244" text-anchor="middle" class="cap">same fixed layout again</text>
<rect x="510" y="202" width="200" height="56" rx="8" class="box"/>
<text x="610" y="226" text-anchor="middle" class="body">Nil</text>
<text x="610" y="244" text-anchor="middle" class="cap">variant with no payload, chain ends</text>
<path d="M230,230 L270,230" style="stroke:var(--ac)" marker-end="url(#mm7b-arrowac)"/>
<path d="M470,230 L510,230" style="stroke:var(--ac)" marker-end="url(#mm7b-arrowac)"/>
<!-- caption -->
<text x="400" y="290" text-anchor="middle" class="cap">Box changes "contains a List" into "points to a List".</text>
<text x="400" y="310" text-anchor="middle" class="cap">The recursion moves to runtime, where it is finite, and the stack size becomes known.</text>
</svg>
</div>

### 2. Large Data (Avoid Stack Overflow)
Moving large structs (e.g., a 1MB buffer) to the heap prevents stack overflows.

```rust
let big_data = Box::new([0u8; 1_000_000]); // Heap-allocated array
```

### 3. Trait Objects (dyn Trait)
Storing heterogeneous types behind a trait interface for [dynamic dispatch](https://mayorana.ch/en/blog/dispatch-performance-rust).

```rust
trait Animal { fn speak(&self); }
struct Cat;
impl Animal for Cat { fn speak(&self) { println!("Meow"); } }

let animals: Vec<Box<dyn Animal>> = vec![Box::new(Cat)]; // Dynamic dispatch
```

### 4. Transferring Ownership Across Threads
`Box` can be used with `std::thread::spawn` to move owned data to another thread.

```rust
let x = Box::new(42);
std::thread::spawn(move || {
    println!("{}", x); // `x` is moved into the thread
});
```

## How Box<T> Differs from Other Pointers

| **Type** | **Ownership** | **Use Case** |
|----------|---------------|--------------|
| `Box<T>` | Owned (unique) | Heap allocation, recursive types |
| `&T`/`&mut T` | Borrowed | Temporary references |
| `Rc<T>` | Shared (reference-counted) | Multiple owners in single-threaded code |
| `Arc<T>` | Shared (atomic refcount) | Thread-safe multiple owners |

## Memory Safety Guarantees

- **No manual `free()`**: Automatically deallocates when `Box` goes out of scope.
- **No null pointers**: `Box` cannot be null (unlike raw pointers).
- **No leaks**: Compiler enforces ownership rules.

## Example: Box vs Stack Allocation

```rust
// Stack (fails if too large)
// let arr = [0u8; 10_000_000]; // Likely stack overflow

// Heap (works)
let arr = Box::new([0u8; 10_000_000]); // Safe
```

## When to reach for `Box`
**Use `Box<T>` when you need**:
- Heap allocation for large or recursive data.
- [Trait objects](https://mayorana.ch/en/blog/object-safety-rust) (`dyn Trait`).
- Explicit ownership with a fixed-size pointer.

**Avoid if**:
- You only need a reference (`&T`).
- You need shared ownership (use `Rc` or `Arc` instead).

Boxing something that already lives on the heap is legal and occasionally useful, but you're
buying a second indirection — the `Box` points at a fresh allocation holding the original
handle, not at the original data.
