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.
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With