Sub topic 1
Anatomy of a Rust Compiler Diagnostic
Prerequisites
This chapter assumes basic Rust syntax, cargo build, cargo run, ownership, and references. You should be able to read a function, a let binding, and a compiler error in a terminal.
Reading a diagnostic
A Rust compiler diagnostic usually contains these parts:
| Part | Purpose |
|---|---|
| Error code | Identifies the error category, such as `E0308` |
| Message | States the immediate problem |
| Primary span | Marks the source location that needs attention |
| Labels | Explain related expressions or types |
| Note and help | Add context or suggest a correction |
Read from the error message to the highlighted source, then inspect the notes and help text. The first error often causes later errors, so do not treat the list as an independent set.
The compile-fix loop with `cargo check`
Use cargo check for a fast validation loop. It type-checks and borrow-checks the project without producing a binary.
- Make one small change.
- Run
cargo check. - Read the first error and its highlighted span.
- Apply or test the suggested fix.
- Check again.
cargo checkKeep the change narrow. Large edits can hide which change resolved the diagnostic or create unrelated errors.
Error codes and `rustc --explain`
An error code provides a focused explanation with examples. For example, E0308 means a type mismatch. Ask rustc for its longer explanation:
rustc --explain E0308The explanation describes the rule behind the error. It does not replace reading your own diagnostic, because your source context determines the correct fix.
> callout note > Treat compiler suggestions as informed proposals. Confirm that a suggestion preserves the intended behavior before applying it.
Fixing mismatched types
A mismatched-types error occurs when an expression has a different type from the type required by its context. A trailing semicolon is a common cause because it changes an expression into a statement returning ().
fn double(x: i32) -> i32 {
x * 2;
}Here, the function promises i32, but its final statement produces (). Remove the semicolon so the expression becomes the return value:
fn double(x: i32) -> i32 {
x * 2
}Other mismatches may require an explicit conversion, a different annotation, or a change to the surrounding API. Do not add casts automatically. First determine which type represents the intended value.
Exercise
What should you inspect first when cargo check reports several errors?
Show answer
Inspect the first error, its primary span, and its labels. Later errors may be consequences of the first problem.