I help a few people learn Rust and I have noticed that explaining ownership up front does not work. Asking works better. Here is the sequence I use.
Start with this and ask: "will it compile?"
fn main() {
let s = String::from("hi");
let t = s;
println!("{}", s);
}
It will not. The error says borrow of moved value. Now ask:
- Who owns the heap buffer with the text "hi" after
let t = s? (t.sis no longer valid.) - Why did the language not just copy it? (Because copying a heap buffer is not free, and the language wants you to see it.)
- If both
sandtpointed to the same buffer, what would happen at the end of the function? (Both would free it. A double free, the classic C bug.) - So what rule prevents that? (Each value has exactly one owner, and it is freed when the owner goes out of scope.)
Only then introduce borrowing: &s is "look but do not take", and the compiler checks the borrow cannot outlive the owner.
The nice part is that everyone who knows C already has the scars that make the rule make sense. The compiler is a very strict colleague who remembers every double free you have ever written.
What question made ownership "click" for you?