CodeBlanks Logo Icon CodeBlanks

Box<T>

Allocate on the heap with Box<T>.

Box<T>

Box<T> is the simplest smart pointer: it puts a value on the heap and has a single owner. When the box goes out of scope, the heap value is dropped too. The content is read with *:

let b = Box::new(41);
let n = *b + 1;          // 42
let buyuk = Box::new([0u8; 1000]);   // 1000 bytes on the heap

Uses: types whose size isn't known at compile time (recursive types, dyn Trait), moving large values without copying.

Box and trait objects

The most common use is keeping different types behind the same interface. Box<dyn Trait> is a "fat pointer": data address + vtable address:

use std::fmt::Display;

let ogeler: Vec<Box<dyn Display>> = vec![Box::new(3), Box::new("üç"), Box::new(3.0)];
for o in &ogeler {
    print!("{o} ");   // 3 üç 3
}

Box is dereferenced automatically when calling methods; b.len() calls the inner value's method.

Practice Boxes

Create Box::new(41) and add 1 to its content. Also create Box::new([0u8; 1000]). Print the sum and the array's length separated by a space.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let b = Box::new(41);
    let n = *b + 1;
    let buyuk = Box::new([0u8; 1000]);
    println!("{} {}", n, buyuk.len());
}

Expected output

42 1000

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How much stack space does a <code>Box&lt;[u8; 1000]&gt;</code> variable take?

  • 0
  • One pointer (8 bytes on a 64-bit system) Correct answer
  • 1000 bytes
  • 1008 bytes

Explanation: The data is on the heap; only the address is on the stack. Moving it means copying 8 bytes.

2 Read the content

Question
let b = Box::new(41);
let n = ____b + 1;   // 42
Answer
let b = Box::new(41);
let n = *b + 1;   // 42

Explanation: * gives the value inside the box.

3 Expression and meaning

Term Meaning
Box::new(5) 5 on the heap
*b Content
Box<dyn Display> Trait object
drop(b) Early drop

All lessons in Intermediate