Stack and heap variables

To understand why we get this problem, we will need to understand in depth how Rust works, and by this I mean at memory level.

Let's start with our variable:

let myvar = 32i32; 

As I've said, in our minds, we will create a myvar variable of type i32 and bind it to the value 32. Rust, on the other hand, does it differently.

Firstly, it identifies that we will need space on the stack for a value that is the size of i32.

Next, it copies the value for 32 into that space allocated on the stack.

Lastly, it binds the binding to the position of the stack allocated block to the variable name.

In other words, the complete opposite to how we do it in our minds.

Let's see what happens when we create another binding, like this:

let myvartwo = myvar; 

The compiler moves the binding to where the data sits on the stack for myvar and then says that that position (and data) belongs to myvartwo. The binding will be transferred. What happens to myvar though? Rust won't allow things to dangle or allow information to be bound to two different objects. Once the binding is transferred, myvar is removed.

The same thing happens if the binding points to something in the heap. Therefore, when we consider let myvec = vec![1i32, 2i32, 3i32];, let myvec = vec![1i32, 2i32, 3i32]; we know how this will work. The compiler knows that it requires space on the heap, enough to hold three elements of type i32. These values are copied into the locations and the base address of the contiguous chunk of memory is bound to myvec.

Now, let's transfer ownership:

let vectwo = myvec; 

Now, vectwo is the only usable binding to the vector on the heap, and myvec gets invalidated.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset