Ownership in a nutshell, by Héla Ben Khalfallah, Jun 1, 2020

How does Rust manage memory ?

  • Stack: It’s a special region of your computer’s memory that stores temporary variables created by each function. When a function exits, all of its variables are popped off of the stack (and hence lost forever). Thus stack variables are local in nature (variable scope, or local).
    • Primitive values such as numbers, characters, and true/false values are stored on the stack (stack is LIFO).
  • Heap : Unlike the stack, variables created on the heap are accessible by any function, anywhere in your program. Heap variables are essentially global in scope.
    • While the value of more complex objects or types that could grow in size are stored in the heap memory.

For examples,

let my_string = "hello";

Data with known size at compile time, i.e. my_string, is stored in stack because we know size of the string literal at compile time.

  • Each value in Rust has a variable that’s called its owner.
  • There can only be one owner at a time.
  • When the owner goes out of scope, the value will be dropped.
fn main() {
    {
        let hello = "Hello, World!";
        println!("{}", hello);
    }
    // varibale hello is now invalid!
    println!("{}", hello);
}