Ownership Rules
- Each value in Rust has an variable. This variable is called Owner
- There can only be one owner at a time (Value cannot be owned by multiple variables)
- When the owner goes out of scope the variable is also dropped
Ownership
In languages like C to allocate memory on the Heap we have to use the new
keyword and to delete the memory we need to use the delete
keyword
Allocation and Deallocation of memory is performed automatically in Rust
Similar to RAII pattern followed in C++
In other languages the variable string2 would become a shallow copy i.e. a pointer pointing to the same memory location as variable string1
In Rust the value of string1 is copied to string2 (Rule 2) and then string1 is invalidated
Since string1 is invalidated unlike in shallow copy Rust calls this operation as Move
This causes the ownership of the variable to be passed to string2 from string1
The clone()
method has to be used to perform the more expensive (deep) copy operation
The scalar datatypes implement a Trait called Copy which allows them to be copied automatically
Move even occurs when a Compound Datatype is passed/ returned from a function
Borrowing Rules
- At any given time, you can either have one mutable reference or any number of immutable reference
- References must always be valid (Invalid references result in compilation error)
Borrowing
Instead of assigning the ownership of a value to different variables we can pass the reference to the value to another variable (borrow the value from owner)
Since the variable that borrowed the value does not own the value when it goes out of scope the value is not cleared
References are immutable by default. We cannot use them to modify the data
To mutate data using references we must create a mutable reference (&mut var1
)
In a given scope there can only be a single mutable reference to specific data
If we create an immutable reference we cannot have a mutable reference to the same data as long as the immutable reference is in scope (Reverse is also true)
We can borrow from an invalid/non-existent owner (Owner has been dereferenced)