4. Understanding Ownership

Learning objectives

Learning objectives

  1. Understand Rust’s ownership system
  2. Work with the borrow checker
  3. Implement the right ownership model at the right time

What Is Ownership?

Moves

let x = String::from("hello");
let x2 = x;
println!("{x}");

Moves

let x = String::from("hello");
take_ownership(x);
println!("{x}");

fn take_ownership(_name: String) {
  ()
}

Moves

let x = String::from("hello");
take_ownership(x.clone());
println!("{x}");

fn take_ownership(_name: String) {
  ()
}

Moves

Stack vs Heap

let x = 1;
println!("{x}");
println!("{x}");

Stack

Heap

Box::new()

let x = Box::new(1);
take_ownership(x);
println!("{x}");

fn take_ownership(_name: Box<i32>) {
  ()
}

Box::new()

References and Borrowing

Immutable references

let x = String::from("hello");
borrow(&x);
println!("{x}");

fn borrow(_name: &String) {
  ()
}

Immutable references

Immutable references

Immutable references

let x = String::from("hello");
let x2 = &x;

borrow(&x);
println!("{x2}");

fn borrow(_name: &String) {
  ()
}

Immutable references

Mutable references

let mut x = String::from("hello");

let x2 = &x;

borrow(&mut x);

println!("{x2}");

fn borrow(_name: &mut String) {
  ()
}

Mutable references

The Slice Type

Slices

String literals are slices

let hello = "hello";
there(hello);

fn there(hello2: &str) {
  println!("{hello2} there")
}

&str as parameters

let hello = String::from("hello");
there(&hello);

fn there(hello2: &str) {
  println!("{hello2} there")
}