The Ownership Rules
Ownership determines responsibility for a value and its cleanup. Passing or assigning a non-Copy value normally moves it; Copy values are copied, and shared-ownership types provide explicit additional rules.
Trace moves, copies and drops without assuming assignment always duplicates a resource.
Two librarians both think they are responsible for returning the same book to the shelf. Either they bump into each other or one finds the book already gone. Rust's heap has the same problem, and ownership solves it with three short rules the compiler enforces on every line.
The rule
One owner at a time; assignment moves; the owner leaving scope drops the value.
- Each value has an owner, the variable holding it.
- There is only one owner at a time.
- When the owner goes out of scope, the value is dropped (for a
String, its heap text is freed).
Rule 2 has a big consequence. Assigning a String, or passing it to a function, moves it:
let title = String::from("Night Garden");
let copy = title; // ownership moves to copy
println!("{title}"); // error[E0382]: borrow of moved value: `title`Only the 24-byte record (pointer, length, capacity) was copied; the heap text was not. If both names stayed valid, both would free the same text at the end of scope. So the compiler treats title as moved: from that line on, any use of it is an error.
Functions work the same way:
fn shelve(book: String) { /* ... */ } // book dropped at the end
let title = String::from("Night Garden");
shelve(title); // moved into the function
// title cannot be used hereA function can hand ownership back by returning the value.
Two escapes:
clone()makes a real, separate copy of the heap data. It costs time and memory, so Rust makes you ask for it.Copytypes are duplicated on assignment instead of moved. These are simple fixed-size values: all integers, floats,bool,char, and tuples or arrays made only of them.let a = 5; let b = a;leaves both usable.