Search code examples
pointersrust

When to use Box instead of reference?


I'm new to Rust and I'm trying to understand when a Box should be used instead of a regular reference.

All the examples I can find show how to use a Box, but none of them explain in what situation you should use them over regular & references.


Solution

  • (Additional to Shepmaster's great answer: another way to think of ownership)

    You always have to think about: where does the value live? 🏠

    For example, data can live on the stack, in some special place of the executable, or in a Box. On the other hand, a reference isn't a place to live in -- it just points to some data that lives somewhere else. So:

    • if you know that the data you want to work with has a home to live in: you can usually just use a reference (address) to just get access to it (visit it ✈).
    • if your data does not have a place to live in, put it in a box to give it a home 🏠 ♥

    The chapters ownership and borrowing in the Rust book are a great way to learn about these concepts.