Sub topic 1
Anatomy of a compiler diagnostic
A rustc diagnostic is a structured report, not a wall of text. Each part has a fixed job, and once you can tell the parts apart you can read most errors in a few seconds. This chapter takes one diagnostic apart piece by piece. Later chapters use that skill on specific error families.
Prerequisites
This chapter assumes you can:
- Write basic Rust: functions,
letbindings, structs, enums, andmatch. - Run
cargo buildandcargo runfrom a terminal and find the project'ssrc/main.rs. - Explain in a sentence what ownership and references are. You don't need to be fluent in them yet.
The sample output below comes from a recent stable toolchain. Exact wording and spacing change between releases, but the structure has stayed the same for years.
A diagnostic from top to bottom
Start with a small program that fails to compile:
fn double(x: i32) -> i32 {
x * 2;
}
fn main() {
println!("{}", double(4));
}Running cargo check prints this:
error[E0308]: mismatched types
--> src/main.rs:1:23
|
1 | fn double(x: i32) -> i32 {
| ------ ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
2 | x * 2;
| - help: remove this semicolon to return this value
For more information about this error, try `rustc --explain E0308`.
error: could not compile `demo` (bin "demo") due to 1 previous errorThe report has five parts. The diagram shows how they relate.
The header: level, code, message
The first line is error[E0308]: mismatched types. It has three pieces.
- The level is
error,warning, or occasionallynoteorhelpwhen they appear on their own. An error stops compilation. A warning does not. - The error code is
E0308. It is a stable identifier for a category of problem. You can search for it and pass it torustc --explain. Not every diagnostic has a code. Many warnings and some errors, such as plain syntax errors, only have a message. - The message is a short, general statement of the problem.
mismatched typesdoesn't say which types. The details come later in the snippet.
The location line
The line --> src/main.rs:1:23 gives file:line:column for the primary span, the code the compiler considers the main cause of the problem. Most editors and terminals let you click this path to jump to the spot. Here that is line 1, column 23, the i32 return type.
The snippet, primary span, and labels
The snippet shows the relevant source lines with a line-number gutter on the left. Under those lines the compiler draws markers.
- A primary span is underlined with carets (
^^^). It marks the main location, and the text after it says what is wrong there:expected i32, found (). - Secondary spans are underlined with dashes (
------). They point to related code that explains why the primary span is wrong. Here the dashes underdoublecarry the label "implicitly returns()as its body has no tail orreturnexpression". - A label is the text attached to a span.
Primary and secondary spans can sit on different lines, or even in different files. In this example the secondary span on line 2 points at the semicolon. Reading the labels in order gives you the whole story. The function promises an i32. Its body ends in a statement, so it returns (). The semicolon is the cause.
Notes and help
Below or inside the snippet you may see extra lines that start with note: or help:.
- A
notegives background: why a rule exists, where a type was defined, or which lint produced a warning. - A
helpsuggests a change. When the suggestion is concrete, it appears inline with a span, ashelp: remove this semicolon to return this valuedoes above.
Treat help text as a lead, not an order. The compiler guesses your intent from the code it can see. Later in this tutorial, the chapter on compiler suggestions covers when it is safe to apply them automatically.
The footer
Two lines close the report. For more information about this error, try rustc --explain E0308 points you to a longer description of the code. error: could not compile ... due to 1 previous error summarizes the run. The count matters because one mistake can produce several errors, as a later chapter explains.
Reading order that works
A reliable routine takes about ten seconds.
- Read the header. Note the code and the general category.
- Read the primary span's label. It states what the compiler found and what it expected.
- Read the secondary labels. They usually explain where the expectation came from.
- Read
noteandhelplines last. They often contain the fix.
Skipping straight to help is tempting. It works for simple cases, but it teaches you nothing, and it can lead you to apply a fix that silences the error without fixing the logic.
Same shape, different content
The structure is identical across error families. Here is a misspelled name:
fn main() {
let count = 3;
println!("{}", cnt);
}error[E0425]: cannot find value `cnt` in this scope
--> src/main.rs:3:20
|
3 | println!("{}", cnt);
| ^^^ help: a local variable with a similar name exists: `count`There is one span, one label, and an inline suggestion. Compare it with a use-after-move error, which has more spans:
fn main() {
let name = String::from("Ferris");
let greeting = name;
println!("{name} {greeting}");
}error[E0382]: borrow of moved value: `name`
--> src/main.rs:4:16
|
2 | let name = String::from("Ferris");
| ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
3 | let greeting = name;
| ---- value moved here
4 | println!("{name} {greeting}");
| ^^^^ value borrowed here after moveThe primary span (carets, line 4) shows where the program broke the rule. The secondary spans (dashes, lines 2 and 3) tell the history: where the value was created and where it was moved. Compiler output for ownership errors often reads as a short story in source order. You don't need to understand the rule yet. You only need to see that the spans narrate it.
Warnings use the same format
Warnings follow the same layout but don't stop the build:
fn main() {
let unused = 10;
println!("hello");
}warning: unused variable: `unused`
--> src/main.rs:2:9
|
2 | let unused = 10;
| ^^^^^^ help: if this is intentional, prefix it with an underscore: `_unused`
|
= note: `#[warn(unused_variables)]` on by defaultTwo things are new here. A line starting with = is a note attached to the whole diagnostic and not to a span. The note also names the lint, unused_variables, that produced the warning. A lint is a check you can raise, lower, or silence with an attribute. Errors from the type checker and borrow checker are not lints. You can't turn them off.
Controlling how much output you see
You will often want less noise or more detail. These options help:
cargo check --message-format shortprints one line per diagnostic, which is useful for a quick scan.cargo check --message-format jsonprints machine-readable diagnostics. Editors andrust-analyzerconsume this form. It carries the same data: code, message, spans, labels, and suggestions.RUST_BACKTRACEdoes not matter here. It applies to runtime panics, not compile errors.
A short table summarizes the vocabulary:
| Term | Marker in output | Meaning |
|---|---|---|
| Primary span | `^^^` carets | The main location of the problem |
| Secondary span | `---` dashes | Related code that explains the cause |
| Label | Text after a span | What the compiler says about that span |
| Note | `note:` or `= note:` | Background or a rule's rationale |
| Help | `help:` | A suggested change |
| Error code | `[E0308]` | A stable identifier for the category |
Common mistakes when reading diagnostics
- Reading only the message.
mismatched typesis almost useless alone. The labelexpected i32, found ()is what tells you what to change. - Editing at the primary span by reflex. As the move example showed, the cause may be on a secondary span.
- Ignoring the count.
due to 1 previous erroranddue to 14 previous errorscall for different strategies. A later chapter covers this. - Treating
helpas authoritative. A suggestion that compiles is not necessarily what you meant.
Exercise
In a diagnostic, the carets (^^^) are under line 8, and a dashed secondary span with the label "value moved here" is under line 5. Which part tells you where the compiler detected the violation, and which part tells you where the move happened? Which line would you most likely edit to resolve it?
Show answer
The primary span (carets, line 8) is where the compiler detected the violation. The secondary span (dashes, line 5) shows where the move happened. The usual fix goes at or near line 5, for example by borrowing instead of moving or by cloning, because the move is the cause. Line 8 is where the symptom appears.
Exercise
Why does the warning for an unused variable include note: #[warn(unused_variables)] on by default, while the E0308 error above has no such line?
Show answer
The unused-variable report comes from a lint, and a lint has a name and a default level that you can change with an attribute such as #[allow(unused_variables)]. E0308 comes from the type checker. It is a hard error with no lint level to adjust, so there is no lint note.