Sub topic 12
Using compiler suggestions and cargo fix safely
This chapter assumes you can read the parts of a rustc diagnostic (code, message, span, labels, notes, help), run cargo check, and use git to commit and diff. It covers when to trust a compiler suggestion, how cargo fix applies suggestions automatically, and how to review the result.
Where suggestions come from
Many diagnostics end with a help: line, or show a corrected snippet with + and - markers. Each of these is a suggestion. A suggestion is a proposed text edit attached to a span, and the compiler also gives it an applicability level. The level says how much the compiler trusts the edit.
| Applicability | Meaning | Applied by `cargo fix`? |
|---|---|---|
| `MachineApplicable` | The edit is certain to be correct and will not change behavior. | Yes |
| `MaybeIncorrect` | The edit may be right, but it is a guess about your intent. | No |
| `HasPlaceholders` | The edit contains a placeholder such as `/* value */` that you must fill in. | No |
| `Unspecified` | The compiler does not know how reliable the edit is. | No |
Only MachineApplicable edits are applied automatically. Treat every other suggestion as advice you must evaluate yourself.
Reading a suggestion critically
A suggestion fixes the symptom the compiler can see. It cannot know what your program is meant to do. Two fixes for the same error can have very different costs.
The use-after-move example from earlier chapters shows this:
fn main() {
let name = String::from("Ferris");
let greeting = name;
println!("{name} {greeting}");
}For this E0382 error, rustc may suggest cloning. The clone compiles, but it allocates a second String. If greeting only needs to read the text, a borrow (let greeting = &name;) is cheaper and expresses the intent better. The compiler cannot tell which you meant, so it offers a fix that makes the program compile and leaves the design choice to you.
Check each suggestion with three questions:
- Does it match what the code is supposed to do, or does it only silence the error?
- Does it change behavior, such as an extra copy, a different type, or a discarded value?
- Does it touch only the line you expect?
Using cargo fix
cargo fix runs the same analysis as cargo check, collects the MachineApplicable suggestions, and writes them to your source files. After it applies fixes, it rebuilds the code. If the fixed code fails to compile, it reverts the change and reports what happened.
This program has four warnings, and each one has a certain fix:
use std::collections::HashMap;
use std::fmt;
fn main() {
let mut count = 3;
if (count > 1) {
println!("count is {count}");
}
}The compiler warns about two unused imports (unused_imports), a mut that is never needed (unused_mut), and redundant parentheses (unused_parens). Commit your work first, then run the fixer and review the result:
git add -A && git commit -m "Before cargo fix"
cargo fix
git diffAfter cargo fix, the file looks like this:
fn main() {
let count = 3;
if count > 1 {
println!("count is {count}");
}
}Every change removes something that had no effect, so none of them can alter behavior. That is why the compiler marks them MachineApplicable.
Why cargo fix refuses a dirty working tree
By default, cargo fix stops if your version control state has uncommitted changes. This protects you. If the tool mixes its edits with yours, you cannot separate them afterward, and you cannot revert only the automatic part. Commit first, so that git diff shows only what the tool did.
The flags below override the safety checks or widen what gets fixed:
| Flag | Effect |
|---|---|
| `--allow-dirty` | Run even with uncommitted changes. |
| `--allow-staged` | Run even with staged changes. |
| `--allow-no-vcs` | Run in a directory that is not under version control. |
| `--all-targets` | Also fix tests, examples, and benches. |
| `--edition` | Migrate code to the next edition. |
| `--broken-code` | Keep fixes even if the result does not compile. |
Avoid --broken-code unless you are in the middle of a large migration and expect to repair the remainder by hand. It disables the check that makes cargo fix safe.
Inspecting applicability yourself
When you are unsure why cargo fix skipped a suggestion, ask the compiler for machine-readable output:
cargo check --message-format=jsonEach diagnostic is one JSON object per line. Suggestions appear inside the children and spans arrays, and each replacement span carries a suggestion_applicability field with one of the values in the table above. A value other than MachineApplicable explains why cargo fix left the edit alone. Editors and tools such as rust-analyzer read the same data to offer quick fixes.
A safe workflow
The loop below combines manual reading with automated fixing. It keeps every automatic change reviewable.
The loop has three habits worth keeping:
- Commit before and after the tool runs, so the automatic edits sit in their own commit.
- Read the diff of every automated change, even a small one.
- Return to manual reading for whatever remains. Errors such as E0308, E0382, and E0502 usually need a design decision, so their suggestions are rarely
MachineApplicable.
Edition migrations
cargo fix --edition prepares a crate for the next Rust edition. It applies rewrites for constructs whose meaning changes, so the code compiles the same way under both editions. The usual steps are:
- Commit your work, and confirm
cargo check --all-targetsis clean. - Run
cargo fix --edition --all-targets. - Change the
editionfield inCargo.tomlto the new edition. - Run
cargo check --all-targetsandcargo testagain.
Do this step before editing Cargo.toml, not after. The migration lints run against the old edition.
Clippy fixes
Clippy lints also carry suggestions. You can apply the machine-applicable ones with:
cargo clippy --fixThe same rules apply: it refuses a dirty tree, and it only applies edits marked MachineApplicable. Clippy style suggestions are more opinionated than compiler warnings, so the diff review matters even more. For example, a rewrite from an index loop to an iterator is correct but changes how the code reads.
Common mistakes
- Running
cargo fixon uncommitted work and using--allow-dirtyto get past the refusal. You lose the ability to see what the tool changed. - Expecting it to repair every error. Errors without a certain fix, such as a type mismatch, remain after the run.
- Accepting a
help:suggestion without reading the whole diagnostic. The notes above it often explain a better option, such as borrowing instead of cloning. - Fixing many errors at once. Later errors can be side effects of earlier ones. Apply suggestions one at a time, starting with the first diagnostic, and rerun
cargo checkbetween edits. - Skipping the tests.
cargo checkproves the code compiles, not that its behavior is unchanged.
Exercise
You run cargo fix and it stops with a message that the working directory is dirty. Your tree contains an hour of uncommitted work. What should you do, and why is --allow-dirty a poor first choice?
Show answer
Commit (or stash) your work, then rerun cargo fix. After the run, git diff shows only the tool's edits, so you can review them and revert them separately with git restore if needed. --allow-dirty makes the tool's edits mix with your own uncommitted edits, so you cannot tell which changes came from which source and cannot undo only the automatic ones.
Exercise
A diagnostic for an E0308 mismatched types error includes a help: line suggesting an as cast. cargo fix does not apply it. Give the likely reason and say what you should check before applying the cast by hand.
Show answer
The suggestion is not MachineApplicable, because the compiler cannot be sure a cast matches your intent. Casts can truncate or change the sign of a value. Before applying it, check that the cast preserves the value range you need, and consider whether a lossless conversion such as From/into or try_from fits better. You can confirm the applicability by running cargo check --message-format=json and reading suggestion_applicability.
Exercise
Why does cargo fix rebuild the project after it applies its edits?
Show answer
To verify that the fixed code still compiles. If the result fails to build, cargo fix reverts the edits it made, so a bad automatic change does not leave you with a broken project. The --broken-code flag turns this protection off.