Sub topic 8
Applying suggested fixes automatically
Clippy does more than report problems. For many lints it also attaches a concrete code change, and cargo clippy --fix can apply that change for you. This chapter explains how that works, which fixes are safe to apply, and how to review the result.
This chapter assumes you can build a Cargo project, read a Clippy diagnostic, and use Git for basic version control. It builds on the earlier chapters about running cargo clippy and about lint levels.
How suggestions work
When Clippy reports a lint, the diagnostic can include a suggestion: a replacement for a span of source code. Each suggestion carries an applicability level that says how much the tool trusts it.
| Applicability | Meaning | Applied by `--fix`? |
|---|---|---|
| `MachineApplicable` | The change is believed to be correct and to keep behavior the same. | Yes |
| `MaybeIncorrect` | The change may be right, but a human should check it. | No |
| `HasPlaceholders` | The suggestion contains a placeholder you must fill in. | No |
| `Unspecified` | The tool did not classify the suggestion. | No |
Only MachineApplicable suggestions are applied automatically. If a lint's output shows a help message such as help: consider using an iterator, but --fix leaves that code alone, the suggestion is probably not machine-applicable. You then have to make the edit yourself.
Not every lint has a suggestion at all. Some lints only point at a problem, for example clippy::too_many_arguments, because there is no single mechanical rewrite.
A worked example
Take the program from the earlier chapter on running Clippy. It uses an index only to read from a vector, which triggers clippy::needless_range_loop.
fn main() {
let v = vec![10, 20, 30];
for i in 0..v.len() {
println!("{}", v[i]);
}
}Running cargo clippy reports a warning that the loop variable i is only used to index v, and it suggests iterating over the vector directly. To apply the suggestion, run:
cargo clippy --fixClippy rewrites the file. The result is the idiomatic form:
fn main() {
let v = vec![10, 20, 30];
for item in &v {
println!("{item}");
}
}Your exact output can differ slightly. Clippy may keep the old {} placeholder style and choose its own variable name, and the name depends on the Clippy version. The important point is that the code now iterates over the elements, and the behavior is unchanged.
What `cargo clippy --fix` does
cargo clippy --fix runs the same analysis as cargo clippy. It then writes machine-applicable suggestions back to your source files. Internally it uses the same mechanism as cargo fix, which applies compiler suggestions, so the two commands share a safety model and most of their flags.
After applying fixes, Cargo checks the project again. If the fixed code fails to compile, Cargo reverts the fix for the affected file and reports the failure. This protects you from a bad suggestion that breaks the build, but it does not protect you from a fix that compiles and changes meaning in a way you did not intend. That is why review matters.
Safety checks and the dirty-tree guard
By default, cargo clippy --fix refuses to run when it would overwrite uncommitted work. If your working tree has uncommitted changes, you see an error saying the working directory is dirty and that you should commit your changes or pass a flag. The reasoning is simple: if the fix changes files you have edited but not saved to version control, you cannot easily separate your edits from the tool's.
Cargo provides flags to override the guard:
--allow-dirtypermits fixing when there are uncommitted changes.--allow-stagedpermits fixing when changes are staged but not committed.--allow-no-vcspermits fixing when the project is not under version control at all.
The strict form for a clean tree is the default. Use the override flags with care:
cargo clippy --fix --allow-dirtyThe recommended habit is to commit or stash your work first, run cargo clippy --fix on a clean tree, and then inspect the changes with git diff. The diff shows exactly what the tool did, and git restore . (or git checkout -- .) undoes it if you dislike the outcome.
Controlling the scope of a fix
cargo clippy --fix accepts the same target-selection flags as cargo clippy. By default it checks only the library and binary targets, so a lint inside a test, example, or benchmark is not fixed unless you include that target.
To fix everything, including tests and examples, run:
cargo clippy --fix --all-targets --all-featuresFeature flags matter because Rust compiles code under #[cfg(feature = "...")] only when that feature is on. A lint in code behind a disabled feature is never seen, and so never fixed. In a workspace, add --workspace to cover every member crate.
You can also steer which lints are fixed by changing their levels on the command line, using the same flags as in the lint levels chapter. For example, to fix only one lint, allow everything else and warn on the one you want:
cargo clippy --fix -- -A clippy::all -W clippy::needless_range_loopHere -A clippy::all allows every default lint, and -W clippy::needless_range_loop re-enables the one you are targeting. This produces a small, focused diff, which is easier to review than a sweep of unrelated changes. Run it once per lint if you want one commit per kind of change.
Reviewing the result
Automatic does not mean unreviewed. A sound routine looks like this:
- Commit or stash your current work so the tree is clean.
- Run
cargo clippy --fixwith the scope you want. - Run
git diffand read every change. - Run
cargo testto confirm behavior. - Run
cargo fmt, because a rewritten expression can leave odd spacing or line breaks. - Commit the result as its own commit, with a message that names the tool and the lint, so reviewers know the change is mechanical.
Step 5 deserves a note. Fixes generate code from templates, and the output is not always in standard style. Running cargo fmt afterward keeps the formatting check in CI passing.
Common errors and edge cases
The working directory is dirty. The guard described above stopped the run. Commit your changes, or pass --allow-dirty if you accept the mixing of edits.
Nothing changed, but warnings remain. The remaining lints have suggestions that are not machine-applicable, or no suggestion at all. Read each diagnostic and edit by hand. Such a help message often says "consider" or shows a placeholder, which signals that a human must decide.
The fix changes behavior subtly. Machine-applicable means the tool believes the rewrite is equivalent, not that it has proven it. Some lints touch code where the difference is observable, for example evaluation order, integer overflow behavior, or the type that an expression infers to. Tests catch many of these cases. A function with no tests gives you less protection, so read the diff more closely there.
Fixes interact with each other. Two suggestions can overlap on the same span. Cargo applies one and may need another pass for the second. If warnings remain after a run that made changes, run the command again. Repeat until the output stops changing.
Generated or macro code. Suggestions inside macro expansions are often skipped, because the tool cannot safely edit code that originates elsewhere. A warning that points into a macro is typically left for you to handle.
Different results across versions. New Clippy releases add lints and change existing suggestions. Pin your toolchain, for example with a rust-toolchain.toml file, so a teammate and your CI produce the same fixes you did.
Using fixes with the rest of your setup
Automatic fixes work together with the configuration you set up in earlier chapters:
- The
[lints]table inCargo.tomlandclippy.tomldecide which lints fire, so they also decide what--fixcan change. Raisingmsrvinclippy.tomlstops Clippy from suggesting APIs newer than your minimum supported Rust version, which also keeps fixes compatible. - Items marked
#[allow(clippy::lint_name)]are skipped, because the lint is silenced there. - In CI, do not run
--fix. CI should only report. The strict checkcargo clippy --all-targets --all-features -- -D warningsfails the build, and a developer applies the fix locally. Letting CI rewrite code hides problems and creates commits nobody reviewed.
Many editors can apply a single suggestion on demand through a quick-fix action powered by rust-analyzer. That gives you a middle path: you accept one fix at a time at the cursor, with the context in front of you, instead of changing the whole project.
Summary
cargo clippy --fix applies only machine-applicable suggestions, rechecks that the code still compiles, and refuses to run on a dirty tree unless you override it. Control its scope with target flags and with lint-level flags. Review the diff, run your tests, and run cargo fmt before committing. Keep fixing in local workflows and keep CI read-only.
Exercise
You run cargo clippy --fix and Cargo stops with an error about a dirty working directory. Name two safe ways to proceed, and say why --allow-dirty is the weaker choice.
Show answer
Commit your changes, or stash them with git stash, and then rerun the command on a clean tree. Both let you review the tool's edits alone with git diff and undo them with git restore .. --allow-dirty works, but it mixes the tool's edits with your uncommitted edits, so you cannot easily review or revert just the automatic changes.
Exercise
After cargo clippy --fix finishes, cargo clippy still prints a warning that has a help: suggestion. Give two possible reasons the fix was not applied, and write the command that would also fix lints in your tests and in code behind feature flags.
Show answer
The suggestion may not be machine-applicable (it is MaybeIncorrect, has placeholders, or is unspecified), or the code may sit in a target or feature that was not compiled, such as a test or a disabled feature. A suggestion inside macro-generated code can also be skipped. The command is cargo clippy --fix --all-targets --all-features.
Exercise
A teammate proposes a CI step that runs cargo clippy --fix and pushes the result back to the branch. Give two reasons to prefer cargo clippy --all-targets --all-features -- -D warnings in CI.
Show answer
The strict check fails the build and reports problems without changing code, so a developer reviews and applies fixes locally. An automatic fix step would create commits nobody reviewed, could change behavior in subtle ways, and could hide recurring problems instead of surfacing them.