Sub topic 3
Error codes and rustc --explain
This chapter assumes you can run cargo check and cargo build, and that you have seen a rustc diagnostic with its message and source labels. You also need a first idea of ownership and references. Here you learn what the error code in a diagnostic is, how to look it up offline, and how to use it to work out a fix.
What an error code is
Most compiler errors start with a code in square brackets:
error[E0308]: mismatched typesThe code is the letter E followed by four digits. Each code names one category of problem, such as a type mismatch (E0308) or a use of a moved value (E0382). The code tells you which rule was broken. The message tells you how that rule was broken in your program.
The two parts change at different rates:
- The message text is written for humans and changes between compiler releases. A tutorial from two years ago may quote wording you no longer see.
- The code is a stable identifier.
E0382has meant "use of moved value" for years, so it is the best thing to search for or paste into a bug report.
Codes also pay off when a diagnostic is long. Several unrelated errors can end with the same line, so scanning for the codes first shows you what kinds of problems you have.
Where the code appears
Every coded diagnostic has the code on its first line. After the last diagnostic, rustc prints a summary that points you to the explanation:
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 move
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0382`.When a build has several different codes, the last line lists them all:
Some errors have detailed explanations: E0308, E0382.
For more information about an error, try `rustc --explain E0308`.The exact column markers and wording vary by compiler version. The code and the final hint line stay the same.
Reading an explanation with rustc --explain
The hint line is a command you can run as written:
rustc --explain E0382This works anywhere. It does not need a Cargo project, a network connection, or a source file, because the explanations ship inside the compiler. Long output may open in a pager, which you leave by pressing q.
An explanation usually has this shape:
- A short description of what the error means.
- A small example that triggers the error.
- One or more corrected examples, often with several alternative fixes.
- Sometimes a longer discussion, for example about
Copytypes or about why a rule exists.
Read the examples before the prose. The erroneous example is usually a few lines long and strips away everything unrelated. Compare it to your own code and ask which line in yours plays the same role. Then look at the fixes and pick the one that fits what your program is meant to do.
An explanation is generic. It describes the rule, not your program, so the fix it shows may not apply directly. Treat it as a map of the options.
You can also read the same text online in the Rust Compiler Error Index, which lists every code on one searchable page. The offline command and the index show the same content for your compiler version, so prefer rustc --explain when your installed version might differ from the web page.
A worked example
Here is the function from the spine that returns the wrong thing:
fn double(x: i32) -> i32 {
x * 2;
}
fn main() {
println!("{}", double(4));
}Running cargo check reports error[E0308]: mismatched types. The label says the function should return i32 but its body evaluates to (). The help message suggests removing the semicolon.
Run the explanation to confirm the rule:
rustc --explain E0308The text says that E0308 is emitted when the type the compiler expected differs from the type it found. The examples show several shapes of this error, so you match your case to one of them. Here, the trailing semicolon turns the last expression into a statement, and a statement has the type (). The fixed function is:
fn double(x: i32) -> i32 {
x * 2
}
fn main() {
println!("{}", double(4));
}This prints 8. The explanation gave you the general rule, and the diagnostic told you which line broke it.
The same lookup, as a loop
The loop starts at the first error because later errors are often side effects of earlier ones. The chapter on cascading errors covers that in detail.
Codes you will meet most often
The codes below are the ones this tutorial returns to. Learning them by sight saves a lookup, though the explanation is always one command away.
| Code | Short meaning | Typical cause |
|---|---|---|
| E0308 | Mismatched types | Wrong type returned or passed, stray semicolon |
| E0425 | Cannot find value in scope | Misspelled or undeclared name |
| E0384 | Cannot assign twice to immutable variable | Missing `mut` |
| E0382 | Use of moved value | Value moved, then used again |
| E0502 | Conflicting borrows | Shared borrow alive during a mutable borrow |
| E0499 | Second mutable borrow | Two `&mut` to the same value at once |
| E0106 | Missing lifetime specifier | Returned reference with no clear source |
| E0597 | Borrowed value does not live long enough | Reference outlives its owner |
| E0277 | Trait bound not satisfied | Type lacks a required trait implementation |
| E0004 | Non-exhaustive patterns | `match` misses a variant |
Diagnostics without a code
Not every diagnostic has a code, and the missing code means different things in different cases.
Some errors have no code because they are not in the catalogue. Syntax errors are the common case. A missing brace produces a message such as error: expected one of ... with no bracketed code. For these, rely on the message and the span. The span is the underlined region of source, and it is often placed where the parser noticed the problem, which can be after the real mistake.
Warnings from lints are a separate case. A lint is an optional check, and each has a name instead of a code:
warning: unused variable: `x`
--> src/main.rs:2:9
|
2 | let x = 5;
| ^ help: if this is intentional, prefix it with an underscore: `_x`
|
= note: `#[warn(unused_variables)]` on by defaultThe note names the lint, unused_variables. You cannot run rustc --explain on a lint name. To see what a lint does, use rustc -W help, or search the lint name in the Rust documentation. You change a lint's level with an attribute such as #![deny(unused_variables)], which turns the warning into a hard error.
A few codes are retired. If you ask for one, the explanation says the code is no longer emitted. That usually means an older tutorial is describing behavior the compiler has since changed, and you should look for the current code in your own output.
Scanning codes quickly
For a long build log, one line per diagnostic is easier to read than the full display:
cargo check --message-format shortEach line shows the file, position, code, and message. You can see at a glance whether you have ten copies of one problem or ten different problems. Switch back to the default format when you need the labels and notes of a specific error.
Using codes when you ask for help
Include the code in the title or first line of any question. Search results and forum threads are indexed by code, so E0502 finds the right discussions faster than a paraphrase of the message. Paste the full diagnostic text, not a screenshot, along with your compiler version from rustc --version. The final chapter shows how to cut the program down to a minimal example.
Exercise
Your build ends with the line "Some errors have detailed explanations: E0382, E0502." Which commands do you run to read both explanations, and do they require a Cargo project?
Show answer
Run rustc --explain E0382 and then rustc --explain E0502. Neither command needs a Cargo project, a source file, or network access, because the explanations are built into the compiler.
Exercise
You see warning: unused variable: count` with the note #[warn(unused_variables)] on by default. Can you run rustc --explain` on it? How would you make the compiler treat it as an error?
Show answer
No. A lint warning has a lint name, here unused_variables, and not an error code, so rustc --explain has nothing to look up. To make it an error, add #![deny(unused_variables)] at the top of the crate (or #[deny(unused_variables)] on an item).
Exercise
This code fails to compile. Name the error code, then fix it using the explanation's approach. fn main() { let total = 0; total += 1; println!("{total}"); }
Show answer
The error is E0384, "cannot assign twice to immutable variable". Declare the binding as mutable with let mut total = 0;. The program then prints 1.