How Rust uses memory

The memory occupied by any Rust program is split into two distinct areas: the heap and the stack. Simply put, the stack contains primitive variables, while the heap stores complex types. As with the mess on my daughter's bedroom floor, a heap can grow and grow until the available memory is exhausted. The stack is faster and simpler but may not grow without limits. Every binding in Rust is in a stack, but those bindings may refer to things in the heap, and elsewhere.

This all relates directly to the string example. The binding myName is in the stack, and refers to a literal static string, my name. That string being static means that it is somewhere in memory when the program starts. Its being static also means that it cannot be changed.

String::new, on the other hand, creates a String in the heap. It is initially empty, but may grow to fill the whole virtual memory space.

Here is an example of a growing String:

let mut myStringOne = "This is my first string ".to_owned(); 
let myStringTwo = "This is my second string. "; 
let myStringThree = "This is my final string"; 
myStringOne = myStringOne + myStringTwo + myStringTwo + myStringThree + myStringTwo; 

One of the ways of creating Strings is to call the to_owned method on a string slice, like we have just done. There are other ways, but this is the most recommended one because it underlines the ownership issue. We'll get back to that later.

Here, the binding myStringOne starts out at 24 characters long, and would be allocated at least that size on the heap. The binding myStringOne is actually a reference to the position on the heap where myStringOne lives.

As we add to myStringOne, the size it occupies on the heap increases; however, the reference to the base position remains the same.

The lifetime and scope of a variable have to be taken into account. For example, if we define a string within part of a function, and then try and access the string outside the function, we get a compiler error.
..................Content has been hidden....................

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