What is Box?
In rust Box
is a smart pointer that gives access to allocate values in heap. It is a smart pointer because the compiler will automatically decide when to free that value in the heap. Also Box values has a single owner which is the reference.
Just like any other value in Rust the value of type Box
also has a single owner, in the above example box_x
is the owner. When the variable box_x
goes out of scope the value allocated in the heap will be freed. Box
is not Copy
so if you pass it as an argument to a function or assign it to a new variable it will obey the Move
semantics.
Accessing values in Box
Box
is part of the safe Rust meaning, it will always point to a valid memory location, it can never point to a NULL
and it works in a well defined manner unless the allocation in heap itself fails because of no free memory in the RAM.
If there is no NULL supported then how to represent missing values?
Here comes Option
with Box
to the rescue.
None
variant of the Option
can be used to denote missing values. unwarpping a None
results in panic
which is still a well defined, reproducible behaviour.
But Why do we need to allocate memory in Heap?
To simplify usage of recursive non cyclic data types like linked list, tree etc.,
You need to transfer the ownership of a value without copying it
Trait objects, that is values that implement a specific trait can be owned using Box.
Last updated