🦀 Rust Beginner

What are Rust's ownership rules?

Answer

Rust's ownership system is governed by three rules enforced at compile time: 1) Each value has exactly one owner — a variable that holds a value is its owner. 2) There can only be one owner at a time — you cannot have two variables that simultaneously own the same data. 3) When the owner goes out of scope, the value is dropped — Rust automatically inserts a drop() call, freeing the memory. When you assign a value to another variable or pass it to a function, ownership moves: the original variable becomes invalid and the compiler rejects any further use of it. This eliminates double-free and use-after-free bugs at compile time without needing a garbage collector.