Rust Ownership

Understanding Rust ownership rules and memory management

Ownership Rules

# 1. Each value has an owner
# 2. Only one owner at a time
# 3. Value dropped when owner goes out of scope

Move Semantics

let s1 = String::from("hello"); # s1 owns the string
let s2 = s1; # ownership moved to s2
// s1 is no longer valid

Copy Types

let x = 5; # i32 implements Copy
let y = x; # x is copied, not moved
println!("{}"{}, x, y); # both x and y are valid

Clone

let s1 = String::from("hello");
let s2 = s1.clone(); # deep copy
println!("{}"{}, s1, s2); # both valid

Function Ownership

fn take_ownership(s: String) { # takes ownership
    println!("{}", s);
} # s dropped here
let s = String::from("hello");
take_ownership(s); # s moved into function
// s no longer valid here