Rust Ownership in Ten Minutes: Nobody Steals Your Car on the Highway

Ever had your car stolen while you were doing 70 on the highway? Neither has Rust, because Rust cares. Learn Rust ownership by building a 25-line word counter, then break it on purpose and meet the compiler that saves you.

Ada Brackett

5 min read

Have you ever had your car stolen out from under you while doing 70 on the highway? Hands on the wheel, coffee in the cup holder, and suddenly the car belongs to somebody else and you're just sitting on the asphalt, still steering?

Yeah. Neither has Rust. Rust checks.

That's Rust ownership in one sentence. Every value has exactly one owner. You can lend it out, but you can't hand over the keys and keep driving. Other languages either let you do it and crash later (C) or hire a garbage collector to follow you around with a clipboard (Java, Go, nearly everyone else). Rust just asks, at compile time, "Whose car is this?" and refuses to build until there's an answer.

Let's build something small and then crash it on purpose. You need Rust (rustup from rust-lang.org), ten minutes and a mild tolerance for being corrected by a compiler.

Get a garage

Bash
cargo new wordcount
cd wordcount

Cargo hands you a src/main.rs that says "Hello, world!", which is adorable. Replace it with a word counter:

Rust
use std::collections::HashMap;

fn count_words(text: &str) -> HashMap<String, usize> {
    let mut counts = HashMap::new();
    for word in text.split_whitespace() {
        let word = word.to_lowercase();
        *counts.entry(word).or_insert(0) += 1;
    }
    counts
}

fn main() {
    let text = String::from("The cat saw the other cat");
    let counts = count_words(&text);

    let mut pairs: Vec<_> = counts.into_iter().collect();
    pairs.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));

    for (word, n) in pairs {
        println!("{word}: {n}");
    }
    println!("I still own the text: {text}");
}

cargo run:

cat: 2
the: 2
other: 1
saw: 1
I still own the text: The cat saw the other cat

Two cats. One of them is "the other cat", and frankly he seems suspicious.

Rust ownership, explained with cars

Three lines are doing all the work.

let text = String::from(...) is buying the car. main owns that string. When main ends, Rust scraps it for you. There's no free() to forget, and no garbage collector standing in the driveway with a clipboard.

count_words(&text) is lending it to a friend. The & means "borrow it, but bring it back, and don't even think about repainting it." count_words takes a &str, which is a look-but-don't-keep view of the text. That's why main can still print the string at the end. The car came home.

counts.into_iter() is selling it. into_iter takes ownership of the whole map and hands out its pairs one at a time. After that line, counts is gone. Try println!("{}", counts.len()); at the bottom and Rust will gently explain that you don't own that any more.

Now crash it (safely)

Let's do the thing other languages let you do. Make count_words take the string instead of borrowing it:

Rust
fn count_words(text: String) -> HashMap<String, usize> {
Rust
let counts = count_words(text);

cargo run, and:

error[E0382]: borrow of moved value: `text`

The compiler points at the line where you handed the keys over, then at the line where you tried to drive away anyway. It's not angry. It's the friend who grabs your arm before you step into traffic, and it also gives you the line numbers.

You've got three ways out, and choosing one is basically the whole Rust experience:

  1. Lend, don't sell. Put the & back. Counting words doesn't need to own the text, any more than reading a map needs you to own the country.
  2. Clone it. count_words(text.clone()) buys your friend an identical car. Totally legal, but it costs memory. Do it when you actually need two cars, not as a way to make the compiler stop talking.
  3. Make them give it back. Return the string along with the map. It works, but it's like lending a car and demanding it back through the window at every stop light. That's the pattern borrowing exists to replace.

The one rule that catches everyone

Borrowing has a second rule. At any moment you can have either lots of people looking at a value (&T) or exactly one person changing it (&mut T), never both at once.

Think of it as no repainting the car while other people are reading the number plate. Inside count_words, counts.entry(word) takes the paintbrush for a split second, bumps a number, and hands the brush back before the next loop. Nobody's watching while the paint is wet, so the compiler is happy.

That rule makes a whole genre of bugs impossible in safe Rust. You can't change a list while you're looping over it, and two threads can't scribble on the same value without a lock. The 3 a.m. "how is this even null" pages mostly just... stop.

Your homework (it's short, I promise)

  • Make the counter ignore punctuation with word.trim_matches(|c: char| !c.is_alphanumeric()). Notice that ownership doesn't care at all.
  • Read a real file with std::fs::read_to_string("notes.txt"). It returns a Result, which is Rust's way of saying "this might go wrong, so plan for it." That's next week's lesson.
  • Chapter 4 of the Rust Book, "Understanding Ownership", is free at doc.rust-lang.org/book and goes deeper, minus the car jokes.

Fair warning: for about a week, the compiler will feel like a backseat driver. Then one day it catches a bug you'd have shipped, and you realise it was a co-pilot the whole time.