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:


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