The three rules
Ownership has three rules:
- Each value has one owner.
- There can be only one owner at a time.
- The owner goes out of scope, the value is dropped.
{
let s = String::from("hi"); // valid
} // s dropped here
When s goes out of scope, its memory is freed automatically.
Borrowing rules
References follow strict rules:
let mut s = String::from("hi");
let r1 = &s; // ok
let r2 = &s; // ok, two immutable borrows
// let r3 = &mut s; // error while r1, r2 exist
You may have many immutable borrows OR one mutable borrow, never both at once. This prevents reads during writes.