Part 01 · Rust Is Not Scary
The Compiler Is Your Teacher
How to read a Rust error line by line. Most of the time the compiler already wrote the fix for you.
⏱ 9 min · Station 9 of 75
The story
Think back to the best teacher you had. They didn't just write a red cross on your homework. They circled the exact line, wrote why it was wrong in the margin, and often wrote the right answer next to it.
The Rust compiler marks your work like that teacher. Most people's first week with Rust feels like being shouted at by error messages. Once you know how to read them, they turn out to be the most helpful error messages of any mainstream language: they say what's wrong, point at the exact characters, and very often write the fix for you. This lesson teaches you to read them, so the rest of the course feels like a conversation instead of a fight.
The idea
Every Rust error has the same five parts. Once you know where each part is, a long error becomes easy to scan:
- What went wrong:
error[E0384]: cannot assign twice to immutable variable `total`. The codeE0384is the error's ID. The words after it are a one-line summary. - Where:
--> src/main.rs:10:9is file, line 10, column 9. Most editors and terminals let you click it. - Your code, marked up: the lines involved, with
^^^^under the main problem and----under related places (here, wheretotalwas first set). - help: the suggested fix, often as a corrected line, with
+under what to add and-under what to remove. - The long version:
rustc --explain E0384prints a full explanation with examples.
Not every error has every part, but they always come in this order. There are also note: lines, which add background ("this is why"), and warnings, which have the same shape but start with warning: and don't stop the build.
Try it: fix a program in three rounds
Here's a short program with three mistakes in it. It's meant to add up a cart and add delivery:
fn total_with_delivery(total: u64) -> u64 {
let delivery = if total >= 100_000 { 0 } else { 6_000 };
total + delivery;
}
fn main() {
let prices = [42_000, 18_550, 15_000];
let total = 0;
for price in prices {
total += price;
}
println!("to pay: {}", total_with_delivery(totl));
}
Round 1. Run cargo check:
error[E0425]: cannot find value `totl` in this scope
--> src/main.rs:12:48
|
12 | println!("to pay: {}", total_with_delivery(totl));
| ^^^^
|
help: a local variable with a similar name exists
|
12 | println!("to pay: {}", total_with_delivery(total));
| +
error[E0308]: mismatched types
--> src/main.rs:1:39
|
1 | fn total_with_delivery(total: u64) -> u64 {
| ------------------- ^^^ expected `u64`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
2 | let delivery = if total >= 100_000 { 0 } else { 6_000 };
3 | total + delivery;
| - help: remove this semicolon to return this value
Some errors have detailed explanations: E0308, E0425.
For more information about an error, try `rustc --explain E0308`.
error: could not compile `bill` (bin "bill") due to 2 previous errors
Two errors. Take them one at a time, from the top:
E0425:totldoesn't exist. The help line spotted the typo: "a local variable with a similar name exists", and showstotalwith a+under the missing letter.E0308: the semicolon on the last line of a function, from the Functions lesson.
Fix the typo only, and check again.
You fixed totl. There were 2 errors. How many will cargo check show now?
error[E0308]: mismatched types
--> src/main.rs:1:39
|
1 | fn total_with_delivery(total: u64) -> u64 {
| ------------------- ^^^ expected `u64`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
2 | let delivery = if total >= 100_000 { 0 } else { 6_000 };
3 | total + delivery;
| - help: remove this semicolon to return this value
error[E0384]: cannot assign twice to immutable variable `total`
--> src/main.rs:10:9
|
8 | let total = 0;
| ----- first assignment to `total`
9 | for price in prices {
10 | total += price;
| ^^^^^^^^^^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
8 | let mut total = 0;
| +++
Some errors have detailed explanations: E0308, E0384.
For more information about an error, try `rustc --explain E0308`.
error: could not compile `bill` (bin "bill") due to 2 previous errors
Still two, and one is new: E0384, total changed without mut. This surprises everyone the first time. It's not that your fix broke something. The compiler works in stages: first it checks that every name exists, then types, then who changes what (the borrow checker). It can't run a later stage until the earlier ones pass. So the error count can stay the same, or even go up, while you're making real progress.
Round 2: remove the semicolon.
error[E0384]: cannot assign twice to immutable variable `total`
--> src/main.rs:10:9
|
8 | let total = 0;
| ----- first assignment to `total`
9 | for price in prices {
10 | total += price;
| ^^^^^^^^^^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
8 | let mut total = 0;
| +++
For more information about this error, try `rustc --explain E0384`.
error: could not compile `bill` (bin "bill") due to 1 previous error
Round 3: add mut, exactly where the +++ shows.
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.03s
to pay: 81550
Zero errors, and the program runs: ৳755.50 of shopping plus ৳60 delivery is 81,550 paisa (৳815.50). Notice what you did: three fixes, and you never had to guess. Each one was written in a help: line.
What the compiler says
Want more than the one-line summary? Ask for the long version:
rustc --explain E0384
The page is written in Markdown; here it is with the ``` fence lines left out:
An immutable variable was reassigned.
Erroneous code example:
fn main() {
let x = 3;
x = 5; // error, reassignment of immutable variable
}
By default, variables in Rust are immutable. To fix this error, add the keyword
`mut` after the keyword `let` when declaring the variable. For example:
fn main() {
let mut x = 3;
x = 5;
}
Alternatively, you might consider initializing a new variable: either with a new
bound name or (by [shadowing]) with the bound name of your existing variable.
For example:
[shadowing]: https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing
fn main() {
let x = 3;
let x = 5;
}
Every error code has a page like this: what the error means, a small example that triggers it, and the usual ways to fix it. Notice it offers two fixes for E0384: add mut, or make a new variable with shadowing. The short help: line only showed the first. When a suggested fix feels wrong for your code, --explain is where to look for the other options. The same pages are online in the Rust error code index.
And when the code compiles, a second teacher can still help. Clippy is Rust's official linter: it knows hundreds of patterns that work but have a clearer or more idiomatic way to write them. Run it with cargo clippy:
fn main() {
let rating = 4;
let in_stock = true;
if rating >= 1 && rating <= 5 {
println!("valid rating");
}
if in_stock == true {
println!("show the Buy button");
}
}
warning: manual `RangeInclusive::contains` implementation
--> src/main.rs:4:8
|
4 | if rating >= 1 && rating <= 5 {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use: `(1..=5).contains(&rating)`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#manual_range_contains
= note: `#[warn(clippy::manual_range_contains)]` on by default
warning: equality checks against true are unnecessary
--> src/main.rs:7:8
|
7 | if in_stock == true {
| ^^^^^^^^^^^^^^^^ help: try: `in_stock`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#bool_comparison
= note: `#[warn(clippy::bool_comparison)]` on by default
warning: `lint` (bin "lint") generated 2 warnings (run `cargo clippy --fix --bin "lint" -p lint -- ` to apply 2 suggestions)
Both are warnings, not errors: the code was correct. Clippy is teaching style: (1..=5).contains(&rating) reads as "rating is between 1 and 5", and if in_stock is clearer than if in_stock == true. The last line even offers cargo clippy --fix to apply the suggestions for you. Running Clippy regularly is one of the fastest ways to learn how experienced Rust developers write.
Under the hood
Why are Rust's errors so good? Partly because the compiler has to know so much: to check ownership and borrowing, it tracks where every value is created, moved, borrowed and changed. When something is wrong, it already has all the facts it needs to explain it, including the other place involved (the ---- line).
It's also on purpose. The Rust project treats a confusing error message as a bug. People file issues about unclear errors, and they get fixed. The "a local variable with a similar name exists" hint is the result of that work.
A few habits that make you fast:
- Read the first error first. Later errors are often caused by earlier ones. Fix the top one, run
cargo checkagain, repeat. - Use
cargo check, notcargo run, while fixing errors. It skips making the program and answers quicker. - Let your editor do it. rust-analyzer shows the same errors inline as you type, and most
help:suggestions are one click away as a quick fix. - Read the
help:line, then think. It's usually right. When it isn't (likeexpectfor an unknown coupon in Why Rust Feels Hard), it still tells you what the compiler needs, and you decide how to give it that.
Compared with other languages
The same typo (totl) in Python and Go. In Python, on a code path only some orders take:
def checkout(total):
if total >= 100_000:
return total
return totl + 6_000 # typo, only on the path with a delivery fee
print(checkout(150_000)) # free delivery: works
print(checkout(81_550)) # pays delivery: crashes
150000
Traceback (most recent call last):
NameError: name 'totl' is not defined. Did you mean: 'total'?
Python's message is helpful too ("Did you mean: 'total'?"), but notice when it appears. The first order worked. Only an order that pays delivery runs the line with the typo. If your tests only tried a big order, this ships to production.
package main
import "fmt"
func checkout(total uint64) uint64 {
if total >= 100_000 {
return total
}
return totl + 6_000 // typo
}
func main() {
fmt.Println(checkout(81_550))
}
# command-line-arguments
./main.go:9:9: undefined: totl
Go catches it before running, with a short message: what and where, no suggestion.
| Python | Go | Rust | |
|---|---|---|---|
| Typo in a name | NameError when that line runs | compile error | compile error |
| Points at exact characters | yes (^^^) | line and column | yes, plus related spots (---) |
| Suggests a fix | sometimes ("Did you mean") | rarely | usually (help: with the corrected line) |
| Long explanation per error | no | no | rustc --explain E.... |
| Style teacher | linters (ruff, pylint) | go vet, staticcheck | cargo clippy |
Key takeaway
Every Rust error has the same shape: what (error[E....] and a summary), where (--> file:line:column), your code with ^^^ under the problem, help with the fix, and rustc --explain for the long version. Fix the first error first and re-run cargo check. The compiler works in stages, so fixing one error can reveal the next, and that is progress, not a step back. When the code compiles, cargo clippy keeps teaching you better style.
Practice
Objective: fix a broken program using only what the compiler tells you.
Challenge: this program should print the average of five ratings. It has three mistakes. Run cargo check, fix the first error, run it again, and repeat until it builds. Don't fix anything the compiler hasn't pointed at yet.
fn average(total: u64, count: u64) -> u64 {
total / count;
}
fn main() {
let ratings = [5, 4, 4, 3, 5];
let sum = 0;
for r in ratings {
sum += r;
}
let avg = average(sum, ratings.len());
println!("average rating: {avg}");
}
Expected result:
average rating: 4
Hint 1
The first E0308 points at the function: look for a semicolon that shouldn't be there.
Hint 2
The second E0308 says it expected u64 and found usize. ratings.len() gives a usize (the type Rust uses for sizes and positions). Convert it with ratings.len() as u64.
Hint 3
After the two type errors are gone, a third error appears that wasn't there before. You've seen it in this lesson already: something changes without mut.
Solution
fn average(total: u64, count: u64) -> u64 {
total / count
}
fn main() {
let ratings = [5, 4, 4, 3, 5];
let mut sum = 0;
for r in ratings {
sum += r;
}
let avg = average(sum, ratings.len() as u64);
println!("average rating: {avg}");
}
The average of 5, 4, 4, 3, 5 is 4.2, but whole-number division gives 4. If you want 4.2, make average return an f64 and divide total as f64 / count as f64. That's Numbers, Text and Booleans again.
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →