Reputation: 3271
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.
Upvotes: 19
Views: 6220
Reputation: 5000
Reference (&) is actually an 8 byte address in machine code. It can be address to location on stack or heap. btw there is no such thing as pointer in machine code. It is still just an address.
Box in machine code is also an 8 byte address and hence the confusion. But Box is address in heap, not stack, while reference (&) can be an address on heap or stack space.
In machine code there is no such thing as a reference or pointer or Box. Just addresses.
Pointer btw is just an address but it is typed. Does not exist in machine code. So when you do pointer operations like ++, it will increment based on size of type thats it. On compilation it will get translated to actual byte increments.
Upvotes: 0
Reputation: 88696
(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.
Upvotes: 30
Reputation: 430841
A Box
denotes that a type is owned and that it is allocated on the heap. A reference (&
) denotes that you are borrowing the value from something else.
You can even get a reference from a Box
(explicit types are not needed here, only shown for clarity):
let boxed: Box<i32> = Box::new(42);
let reference: &i32 = &boxed;
The primary distinction boils down to ownership. When you own a value, you can do more things to it, such as destroying it or controlling its mutability.
Heap vs stack is also important, but less immediately so. Stacks tend to have a fixed size that is relatively small (on my machine it's 8MiB), so declaring large variables on the stack can lead to exhausting that memory. The heap tends to be bigger, conceptually addressing 2^32 or 2^48 bytes.
The Rust Programming Language has a section on ownership as well as a section on the stack and the heap; I'd encourage you to read both.
Upvotes: 20