Rust for Pythonistas

Lesson 15 of 26

Reading compiler errors

Python finds most mistakes while the program runs, and only on lines that actually run. Rust finds them before the program runs. That's why you'll spend more time reading compiler errors than reading crashes. The good news: Rust's errors are some of the most helpful of any language, and they often include the fix.

Every error has the same shape. Read it from the top:

  1. error[E0308]: mismatched types: what went wrong, plus a code you can look up.
  2. --> src/main.rs:2:20: where (file, line, column).
  3. The code itself, with ^^^^ under the exact problem and ---- under related places, each with a short label.
  4. help: lines: a suggested fix. Lines starting with + show code to add, and lines starting with - show code to remove, like a diff.
  5. rustc --explain E0308 prints a longer explanation with examples.

One golden rule: fix the first error first. Later errors are often side effects of the first one.

Anatomy: mismatched types

Python type hints are not checked when the program runs, so the mistake only shows up later as a TypeError. Rust checks types before running. The ^^^^ marks the wrong value and the --- marks the place that set the expectation.

Python
age: int = "42"
print(age + 1)
Rust
fn main() {
    let age: u32 = "42";
    println!("{}", age + 1);
}

A typo on a line that rarely runs

The Python script runs fine. The bug is hiding in the admin branch and will crash with NameError on the day an admin logs in. Rust checks every line, including ones that don't run today. The help: block is a diff: - is the current line, + is the suggested one.

Python
def greet(name):
    if name == "admin":
        print(f"Welcome back, {nmae}")
    else:
        print(f"Hello, {name}")

greet("ann")
Rust
fn greet(name: &str) {
    if name == "admin" {
        println!("Welcome back, {nmae}");
    } else {
        println!("Hello, {name}");
    }
}

fn main() {
    greet("ann");
}
Output
Hello, ann

A story in labels: use after move

Some errors point at several lines. Read the labels in line order and they tell a story: "names has a type that is not Copy" → "value moved here" → "value borrowed here after move". The help: shows the fix with ++++++++ under the added characters. (Lesson 13 covers moves.)

Python
names = ["Ann", "Bob"]
backup = names
print(f"{len(names)} names")
print(backup)
Rust
fn main() {
    let names = vec!["Ann", "Bob"];
    let backup = names;
    println!("{} names", names.len());
    println!("{:?}", backup);
}
Output
2 names
['Ann', 'Bob']

The help: line is often the whole fix

Python lists can always be changed. In Rust you must say mut (lesson 3). The +++ under mut means "add exactly these characters here". Many everyday errors are fixed by doing what help: says.

Python
names = []
names.append("Ann")
print(names)
Rust
fn main() {
    let names = Vec::new();
    names.push("Ann");
    println!("{:?}", names);
}
Output
['Ann']

Wrong method name

Python's AttributeError becomes Rust's E0599. The compiler knows every method that exists on the type and suggests the closest match.

Python
words = ["a", "b"]
n = words.length()
print(n)
Rust
fn main() {
    let words = vec!["a", "b"];
    let n = words.length();
    println!("{n}");
}

Where the Python analogy breaks

Cheat card

PythonRust
TypeError # at run timeerror[E0308]: mismatched types
NameError # at run timeerror[E0425]: cannot find value
AttributeError # at run timeerror[E0599]: no method named ... found
x = 1 x = 2 # always allowederror[E0384]: cannot assign twice to immutable variable
items.append(x) # always allowederror[E0596]: cannot borrow as mutable
b = a # shares the listerror[E0382]: borrow of moved value
# change a list while looping over iterror[E0502]: cannot borrow as mutable because it is also borrowed as immutable
match x: # no case _ is fineerror[E0004]: non-exhaustive patterns
# duck typing fails at call timeerror[E0277]: the trait bound ... is not satisfied
mypy app.pycargo check // fast: errors only, no build
help(thing)rustc --explain E0382

← Traits instead of duck typing Building and running a real program →