Back to Blog

Rust Ownership Explained - Move, Clone, Borrow & References | Memory Safety Tutorial

Sandy LaneSandy Lane

Video: Rust Ownership Explained - Move, Clone, Borrow & References | Memory Safety Tutorial by Taught by Celeste AI - AI Coding Coach

Watch full page →

Rust Ownership Explained - Move, Clone, Borrow & References

Rust's ownership system is central to its memory safety guarantees without needing a garbage collector. By enforcing strict ownership rules, Rust ensures values have a single owner and memory is freed automatically when that owner goes out of scope. This tutorial covers ownership, move semantics, cloning, copying, and borrowing with references, including mutable references.

Code

fn main() {
  // Move semantics: ownership moves from s1 to s2
  let s1 = String::from("hello");
  let s2 = s1;
  // println!("s1 = {}", s1); // Error: s1 is no longer valid after move
  println!("s2 = {}", s2);

  // Clone: deep copy of heap data, both s1 and s2 are valid
  let s1 = String::from("hello");
  let s2 = s1.clone();
  println!("s1 = {}", s1);
  println!("s2 = {}", s2);

  // Copy trait: integers are copied automatically on assignment
  let x = 5;
  let y = x; // x is copied, still valid
  println!("x = {}, y = {}", x, y);

  // Borrowing with references: function borrows string without ownership
  fn calculate_length(s: &String) -> usize {
    s.len()
  }
  let s1 = String::from("hello");
  let len = calculate_length(&s1);
  println!("Length of '{}' is {}", s1, len);

  // Mutable references: allow modifying borrowed value
  fn add_world(s: &mut String) {
    s.push_str(", world");
  }
  let mut s2 = String::from("hello");
  add_world(&mut s2);
  println!("Modified string: {}", s2);
}

Key Points

  • Each value in Rust has exactly one owner at a time, ensuring clear responsibility for memory.
  • When the owner goes out of scope, Rust automatically drops the value and frees memory.
  • Move semantics transfer ownership, invalidating the original variable for heap data.
  • Clone creates a deep copy, allowing multiple independent owners of heap data.
  • References (&) enable borrowing without taking ownership, with &mut allowing mutable borrowing.