Ownership is Rust’s unique feature that ensures memory safety without garbage collection.

Ownership Rules

  1. Each value has a single owner
  2. Only one owner at a time
  3. When owner goes out of scope, value is dropped
let s = String::from("hello");
// s owns the string

Moving

let s1 = String::from("hello");
let s2 = s1; // s1 is moved to s2
// s1 is no longer valid

Borrowing

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

let s = String::from("hello");
let len = calculate_length(&s); // Borrowing

Mutable References

fn change(s: &mut String) {
    s.push_str(", world");
}

let mut s = String::from("hello");
change(&mut s);

Best Practices

  1. Use references when possible
  2. Understand ownership rules
  3. Avoid unnecessary moves
  4. Use clone() sparingly
  5. Leverage the borrow checker

Conclusion

Master Rust ownership for memory-safe systems programming! 🦀