0
0
Rustprogramming~5 mins

Box pointer in Rust

Choose your learning style9 modes available
Introduction

A Box pointer lets you store data on the heap instead of the stack. This helps when you want to keep data alive or handle big data easily.

When you want to store a large value but keep a small pointer on the stack.
When you need to transfer ownership of data safely between parts of your program.
When you want to create recursive data structures like linked lists or trees.
When you want to control when data is cleaned up by Rust automatically.
Syntax
Rust
let b = Box::new(value);

Box::new(value) creates a new Box pointer holding value on the heap.

The variable b holds the pointer, not the actual data.

Examples
This creates a Box pointer holding the number 5 on the heap.
Rust
let b = Box::new(5);
This stores a string on the heap using a Box pointer.
Rust
let b = Box::new(String::from("hello"));
This shows how to pass a Box pointer to a function, transferring ownership.
Rust
fn take_box(b: Box<i32>) {
    println!("Value inside box: {}", b);
}

fn main() {
    let b = Box::new(10);
    take_box(b);
}
Sample Program

This program creates a Box pointer holding the number 42 and prints it.

Rust
fn main() {
    let b = Box::new(42);
    println!("Box points to: {}", b);
}
OutputSuccess
Important Notes

Box pointers automatically free their data when they go out of scope.

You cannot copy a Box pointer; ownership moves when you assign or pass it.

Box is useful for recursive types because Rust needs a fixed size on the stack.

Summary

Box pointer stores data on the heap and keeps a pointer on the stack.

Use Box to manage ownership and heap allocation safely.

Box helps with big data and recursive structures.