GGistDev

Ownership in Rust

Ownership ensures memory safety without a GC. Each value has a single owner; ownership moves by default.

Moves and copies

Types that implement Copy (e.g., integers) are copied; others move on assignment/passing.

let a = String::from("hi");
let b = a;              // move; a is invalid
// println!("{}", a);  // error: use of moved value

let x = 1;
let y = x;              // x is Copy; still usable

Borrowing references

Borrow immutably &T or mutably &mut T. At most one &mut or any number of & at a time.

let mut s = String::from("hi");
let r1 = &s; let r2 = &s;   // ok: multiple immutable borrows
// let r3 = &mut s;         // error if immutable borrows exist
let r3 = &mut s;            // ok after r1/r2 go out of scope

Drops (RAII)

Values are dropped when they go out of scope; use RAII to release resources automatically.

{
    let f = std::fs::File::create("out.txt").unwrap();
} // f closed here

Cloning

Explicitly duplicate heap data with clone.

let s1 = String::from("hi");
let s2 = s1.clone();

Slices and views

Borrowed views (&[T], &str) reference data without taking ownership.

Summary

  • Moves transfer ownership; Copy types duplicate implicitly
  • Borrow via &T/&mut T under aliasing rules; drops free resources at scope end
  • clone duplicates owned data; slices borrow views