Abstract
-
Ownership refers to program variables’ ability to access to a piece of data allocated in the Heap Segment
-
Ownership is a way to manage the heap segment, or in other sense, manage Pointer
- All data in the heap segment must has only one owner aka variable
- Rust deallocates heap data automatically once its owner goes out of scope (got removed from the Stack Segment) - Box Deallocation Principle
- Ownership can be transferred to other variables by moves, which happen on assignments and function calls - Moved Heap Data Principle
- Heap data can only be accessed through its current owner, not a previous owner - Moved Heap Data Principle
- This enables Rust to make Memory Safety guarantees without needing a Garbage Collector which is a big hit to the performance
Caution
Rust Compiler will not compile if there is a transfer of ownership in a if else statement and we are using the Rust Box that transfers ownership in the if else statement after the if else statement regardless if the if else statement will execute or not
Verbose Code
We need to create new Rust Box after we transfer the ownership to function parameters due to Moved Heap Data Principle. See References and Borrowing for more details
This can be handled with Rust Borrowing
Box Deallocation Principle
- If a variable owns a Rust Box, when Rust deallocates the variable’s frame in Stack Segment, then Rust deallocates the box’s Heap Segment
- Refer to Box’s Owner Manages Deallocation
Note
The key idea is that when a rust box is passed to function aka a new Stack Frame, its memory is deallocated after function ends.
Therefore the data is still available in heap segment after the ownership is transferred
Moved Heap Data Principle
- If a variable
x
moves ownership of data in Heap Segment to another variabley
, thenx
cannot be used after the move - Refer to Variables Cannot Be Used After Being Moved
Cloning Avoids Moves
- In some use cases, we still want to keep a copy of original data in the Heap Segment
- We can do it by calling
clone()
on the Rust Box which create a new copy of original data in the heap segment, and we can assign the ownership of this new copy to other parts of the program to manipulate, and the ownership of the original piece of data is left untouched - Refer to Cloning Avoids Moves