Ownership In Rust
In this article, we will learn about ownership in Rust.
fn main() {
let i = 5;//on stack
let j = i;//on stack
println!("i = {i}, j = {j}");
let str = String::from("theloveoftechI");
let str1 = str.clone();
println!("{str}, {str1}");
let mv_str = str;
println!("{mv_str}");
//println!("{str}"); //This is problematic
}
Variables are allocated on the stack or on the heap.
We can only push an item on the top of the stack. We can also pop an item from the top of the stack. Variables on the stack have fixed sizes. All variables are allocated on the stack when a function is called.
In the case of a heap, space is allocated based on the size of the data. If we want to grow a particular vegetable in the garden, so we reserve a certain area for that vegetable.
In the case of i and j, both are on the stack and the value of i is being copied in j.
In the case of str, str works as a pointer and is allocated on the stack because its size is fixed. But the real data, in this case, theloveoftechI allocated on the heap and str points to this.
When str goes out of the scope, a drop method is called by the Rust compiler to de-allocate the data associated with the str. When a clone method is called on the str,
a new copy of the data(theloveoftechI) is allocated to the heap. Both str and str1 will be de-allocated independently when goes out of scope.
In the case of mv_str, both mv_str and str point to the same data on the heap. So, the data on the heap will be de-allocated twice when str and mv_str go out of scope.
To get rid of this problem, the Rust compiler invalidates the str. It means no drop method is called when str goes out of scope. Also, we can't use str any longer.
Here, ownership is at play. In this case, ownership has been transferred from str to mv_str. In another word, ownership has moved from str to mv_str. Only when a variable with ownership goes out of scope, the drop method is called.
See it running on YouTube.
Happy reading. Keep in touch.
Comments
Post a Comment