πŸ“¦
World 15 Β· Smart Pointers

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.

New word A pointer is like a tag or an address. It doesn't hold the value itself β€” it just tells you where the value is kept.
Think of it like this… The stack of books is your value, the storeroom is the heap, and the little tag in your pocket is the Box. The tag is small and easy to carry, even when the thing it points to is huge!

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.
Ferris says: A Box owns just one thing, and when the Box goes away, the thing in the storeroom is cleaned up too. Tidy! πŸ¦€
Try this! Change the 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. πŸ“¦

You learned… A 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! πŸ‘₯