Rules

  1. Each value has an owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value will be dropped.

e.g. ownership of the "RUST" value stays with s1

fn main() {
    let s1 = String::from("RUST");
    let len = calculate_length(&s1);
    println!("Length of '{}' is {}.", s1, len);
}

fn calculate_length(s: &String) -> usize{
    s.len()
}

e.g. ownership moved to s2, so this will not compile

fn main() {
    let s1 = String::from("RUST");
    let s2 = s1;
    println!("{}", s1);
}

e.g. falling out of scope

fn main (){
    let s1 = String::from("RUST");
    let len = calculate_length(&s1);
    println!("The length of {} is {}", s1, len);
}

// s1 goes out of scope and its value will be dropped out of memory.

fn printLost(s: &string){
    println!("{}", &s1);
}

fn calculate_length(s: &String) -> usize{
    s.len()
}