rjpatil53@gmail.com

Ownership in Rust

15/01/2024
Rust

A quick rundown of concepts in Rust ownership system.


Memory management in Rust

The runtime memory of a Rust program consists of two parts: a stack and a heap

Stack:

Heap

Ownership system

Rust uses a set of rules at compile time to check for possible undefined behaviours in the program. This check ensures that the program can be run safely and efficiently.

Ownership rules

  1. Each value in Rust has a variable that’s called its owner.

    let s: String = String::from("Hello");  // s is the owner of the string "Hello". 
    
    let x: i32 = 5; // x is the owner of the value 5. 
  2. There can only be one owner at a time.

    let s1: String = String::from("Hello");  // `s1` is the owner of the string "Hello". 
    let s2: String = s1;  // `s2` is now the owner of the string "Hello".
    // println!("s1 was {s1}"); // Cannot use `s1` as it does not point to anything.
    println!("s2 is {s2}");
    
    let x: i32 = 5; // `x` is the owner of the value 5. 
    // Variables stored in stack are copied instead of moving.
    let y: i32 = x; // `y` is now the owner of copy of value 5.
    println!("x is {x} and y is {y}");
  3. Variables cannot be used after being moved.

    let s1: String = String::from("Hello");
    let s2: String = s1;
    let s3: String = s2.clone();
    // Following line will throw an error
    // Value of s1 was moved to s2, so s1 does not point to any value.
    // println!("s1 is {s1}");
    println!("s2 is {s2} and s3 is {s3}"); // this works as `clone` does not move value of s2
    
    
    let x: i32 = 5; // x is the owner of the value 5. 
    // Variables stored in stack are copied instead of moving.
    let y: i32 = x; // y is now the owner of copy of value 5.
    println!("x={x} and y={y}"); // This works as value of x was never moved.
  4. When the owner goes out of scope, the value will be dropped.

    fn greet(){
        // name is the owner of "John".
        // Heap contains the string "John" 
        // Stack contains the variable `name` which stores reference to "John" in the heap
        let name: String = String::from("John");  
        
        println!("Hello {name}!");
    } // Frame for `greet` function  with `name` variable is dropped here.
    // As `name` was the owner of "John" string in the heap, the string value is also dropped.

References in Rust

Reference permissions