Sub topic 2
The compile-fix loop with cargo check
This chapter assumes you can run cargo build and cargo run, and that you can read the parts of a rustc diagnostic: the error code, message, labels, and help text. You don't need to know how to fix any particular error yet. The goal here is a repeatable workflow that you can apply to every error in the rest of this tutorial.
Why a loop
Rust programs rarely compile on the first try, and that is normal. The compiler does a lot of checking that other languages leave to runtime: types, ownership, borrowing, and exhaustiveness. A productive Rust session is a tight cycle: edit a little, ask the compiler, read what it says, and edit again. The faster each pass of the cycle, the less the errors cost you.
What cargo check does
cargo check runs the front half of the compiler on your crate. It parses the code, resolves names, type-checks, and borrow-checks. It then stops. It does not generate machine code and does not link a binary.
cargo checkOn success it prints something like this:
Checking demo v0.1.0 (/home/you/demo)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31sThe word Checking (instead of Compiling) tells you that no executable was produced. Cargo stores only metadata for the crate under target/. Skipping code generation and linking makes cargo check noticeably faster than cargo build, especially on larger projects. Nearly every error in this tutorial comes from the stages that cargo check runs, so you lose nothing by using it.
| Command | Parses, resolves, type-checks, borrow-checks | Generates code and links | Produces a runnable binary |
|---|---|---|---|
| `cargo check` | Yes | No | No |
| `cargo build` | Yes | Yes | Yes |
| `cargo run` | Yes | Yes | Yes, then runs it |
The loop itself
The loop has five steps.
- Run
cargo check. - Read the first error from the top, including the code, message, and labels.
- Decide on a cause. If the message is unclear, run
rustc --explainwith the error code. - Make one small change.
- Run
cargo checkagain.
Repeat until the output is clean, then run cargo build or cargo run once to confirm the program works.
The loop depends on two habits.
- Fix one thing at a time. If you change five places and the output gets worse, you won't know which change caused it.
- Start at the top. Later errors are often consequences of earlier ones. A later chapter covers this in detail. For now, treat the first error as the one to fix.
A worked pass through the loop
Here is a function that computes the average of a slice. It contains mistakes.
fn average(values: &[i32]) -> f64 {
let sum: i32 = 0;
for v in values {
sum += v;
}
sum / values.len()
}
fn main() {
println!("{}", average(&[1, 2, 3]));
}Run cargo check. The first diagnostics you see are type errors on the last line. sum is an i32, values.len() is a usize, and the function promises an f64. Rust has no implicit numeric conversions, so the compiler rejects the division (an unsatisfied trait bound, E0277) and the mismatch with the return type.
You might expect to see the other mistake too. The binding sum is not declared mut, so sum += v is an assignment to an immutable variable (E0384). That error does not appear yet. The borrow checker generally does not run on a function that still has type errors, so you only see the immutability error after the type errors are gone. Errors arrive in phases, and fixing one phase can reveal the next. This is not a sign that you are making things worse.
Fix the types first, with explicit conversions:
fn average(values: &[i32]) -> f64 {
let sum: i32 = 0;
for v in values {
sum += v;
}
sum as f64 / values.len() as f64
}
fn main() {
println!("{}", average(&[1, 2, 3]));
}Run cargo check again. The type errors are gone, and now the immutability error appears, pointing at sum += v and suggesting that you make the binding mutable. Apply that one change:
fn average(values: &[i32]) -> f64 {
let mut sum: i32 = 0;
for v in values {
sum += v;
}
sum as f64 / values.len() as f64
}
fn main() {
println!("{}", average(&[1, 2, 3]));
}cargo check now finishes cleanly. Run cargo run and the program prints 2. Two passes through the loop fixed two separate problems.
Reading the end of the output
Cargo ends a failed run with a summary line:
error: could not compile `demo` (bin "demo") due to 2 previous errorsThis line tells you how many errors remain. Watch the number across passes. When it drops, you made progress, even if the remaining error looks new. Cargo also exits with a non-zero status when compilation fails, which matters if you chain commands in a script or in continuous integration.
Warnings are reported separately and do not make the run fail. Read them, because many warn about real problems such as unused variables or unused Result values, but fix errors first.
Useful flags
You can adjust cargo check to fit the situation.
cargo check --message-format shortprints each diagnostic on one line. This is useful when you have many errors and want to scan them, but you lose the labels and help text. Switch back to the default format when you need to understand an error.cargo check --all-targetsalso checks tests, examples, and benchmarks. A plaincargo checkonly covers the library and binaries, so code inside#[cfg(test)]modules is not checked. If a latercargo testshows errors thatcargo checkmissed, this is the usual reason.cargo check --workspacechecks every crate in a workspace.cargo check -p namechecks one crate by name.cargo check --testschecks the test targets without the benchmarks and examples.
cargo check --all-targets
cargo check --message-format short
rustc --explain E0384The last command runs outside cargo. rustc --explain takes an error code and prints a long description with examples. The next chapter covers it in detail.
What cargo check cannot tell you
cargo check catches the large majority of errors, but not all of them. Know these gaps so a clean check does not mislead you.
- Linker errors. Missing system libraries or duplicate symbols appear only when the binary is linked, so only
cargo buildfinds them. - Errors that appear after code generation begins. A small number of errors depend on how generic code is instantiated, and they can surface only during a full build.
- Everything at runtime. Panics, logic errors, integer overflow in release builds, and wrong output are all invisible to the compiler.
- Unchecked targets. As noted above, tests and examples are skipped unless you ask for them.
A good rhythm is to run cargo check after every small edit, cargo check --all-targets before you commit, and a full cargo build or cargo test before you consider the work done.
Common mistakes in the loop
- Fixing from the bottom of the output. Terminal output scrolls, so the last error is the one closest to your cursor. It is often a consequence of an earlier error. Scroll up to the first one.
- Making several changes per pass. It becomes hard to tell which change helped.
- Ignoring the help line. Many diagnostics include a
help:line with the exact edit. Read it before you guess. - Treating a clean
cargo checkas done. Run the program and the tests too. - Silencing instead of fixing. Adding
#[allow(...)]or_prefixes to hide a warning removes the signal without addressing the cause. Do it only when you have decided the warning is wrong for your case.
Exercise
You run cargo check and it prints 14 errors. Which one should you read and fix first, and what should you do after the fix?
Show answer
Read and fix the first error at the top of the output. Later errors are often consequences of it. After one small fix, run cargo check again and look at the new error count and the new first error. Repeat until the output is clean.
Exercise
A function contains both a type error and an assignment to an immutable variable. After you fix the type error, a new E0384 error appears that was not there before. Did your fix break something? Explain.
Show answer
No. The borrow checker generally does not run on a function that still has type errors, so the immutability error was hidden until the type errors were gone. Compiler errors arrive in phases, and fixing one phase can reveal the next. The new error was already present in your code.
Exercise
Your project passes cargo check, but cargo test reports a compile error in a #[cfg(test)] module. Why did cargo check miss it, and which command would have caught it?
Show answer
A plain cargo check only checks the library and binary targets, so test code is not compiled. cargo check --all-targets (or cargo check --tests) includes the test targets and would have reported the error.