Box: A Pointer to the Heap
Imagine you have a huge stack of books thatβs too heavy to carry around. So you keep it safe in a storeroom, and you carry a little tag in your pocket that says where it is. In Rust, a Box works just like that tag! π¦
What is a Box?
Your computer has two places to keep things. One is a small, super-fast space
(called the stack), and the other is a big, roomy space (called the heap).
A Box<T> puts your value in the big roomy heap, and keeps a tiny pointer to it.
Making a Box
You make a Box with Box::new(...). Then you can use it almost like a normal
value β Rust knows how to follow the tag for you.
The number 5 is tucked away in the big storeroom (the heap), and b is the
little tag pointing to it. When we print b, Rust follows the tag and shows us
the 5. π
When is a Box handy?
- π¦ When something is really big and youβd rather carry a small tag.
- πͺ When a shape holds more of itself inside (like nesting dolls). These are called recursive shapes, and a Box helps Rust figure out the size.
5 inside Box::new to any number you like, then
press βΆ Run. Try a bigger number too!
Quick quiz
What does a Box<T> do?
Yes! A Box keeps the value in the big heap storeroom and holds a tiny pointer (a tag) to find it. π¦
Box<T> stores a value in the heap and keeps a
small pointer to it β perfect for big things or nesting shapes.
A Box has just one owner. But what if several parts of your
program need to share the same thing? Next up: Rc: Sharing
Ownership! π₯