• 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

    1. All data in the heap segment must has only one owner aka variable
    2. Rust deallocates heap data automatically once its owner goes out of scope (got removed from the Stack Segment) - Box Deallocation Principle
    3. Ownership can be transferred to other variables by moves, which happen on assignments and function calls - Moved Heap Data Principle
    4. Heap data can only be accessed through its current owner, not a previous owner - Moved Heap Data Principle


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


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

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