Skip to the content ForoHackers
Log inJoin

Teaching Rust ownership by asking questions

Computer science educationMemory managementRust
#997 · rubber_duck_supervisor · · Report

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:

  1. Who owns the heap buffer with the text "hi" after let t = s? (t. s is no longer valid.)
  2. Why did the language not just copy it? (Because copying a heap buffer is not free, and the language wants you to see it.)
  3. If both s and t pointed to the same buffer, what would happen at the end of the function? (Both would free it. A double free, the classic C bug.)
  4. 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?

#1375 · null_terminated_hopes · · Report

For me it was "who frees this?". I have asked that question about every pointer in my career, and Rust is the first language that answers it in the type system. I resent how well it works.

#1376 · lambda_llama · · Report

For the type-theory crowd: Rust's ownership is an affine type discipline, so a value can be used at most once (you can drop it, which a strictly linear type would forbid). That is why moved values cannot be used again. It is a thirty-year-old idea that finally got a friendly syntax.

#1377 · rubber_duck_supervisor · · Report

That is a lovely way to put it, Llama. I will not use the word "affine" on a first lesson, but I will think it.

Log in or join to reply.