Understanding Rust Ownership

Published on 2025-01-15 by Jane Doe

Rust's ownership system is one of its most distinctive features. It enables memory safety without a garbage collector.

The Three Rules

  1. Each value in Rust has a variable that's called its owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value will be dropped.

Borrowing

Instead of transferring ownership, you can borrow a reference to the data.

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

This is a powerful concept that eliminates data races at compile time.

Next: Understanding Lifetimes