Skip to main content
InterviewHubPRO
Section Overview
Q14

Question 14 of 50

Part 2: Core Architecture & Implementation (Mid-Level)

28%
Rust Systems & Tokio (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)

What is `Box<T>` and when should you use it?

senior LevelCode ExampleSystem Design

In Simple Words: Box<T> is the simplest smart pointer that allocates memory on the Heap:

  • When the box goes out of scope, its heap data is freed.
  • Primary Use Cases:
    1. Storing data of unknown size at compile time (e.g. Recursive Data Types like Linked Lists or Abstract Syntax Trees):
      rust
      enum List {
          Cons(i32, Box<List>), // Recursive type requires Box!
          Nil,
      }
      
    2. Transferring ownership of large data structures without copying thousands of bytes on the stack.
    3. Trait Objects (Box<dyn Trait>).