Sub topic 5
Finding problems with cargo clippy
This chapter assumes you can build a Cargo project, read basic Rust (ownership, borrowing, iterators), and use a terminal. You do not need to know anything about Clippy yet. By the end you will be able to run it, read what it prints, and decide what to do about each finding.
What Clippy is
Clippy is a linter for Rust. A linter is a tool that reads your code and reports patterns that are likely to be bugs, slow, or hard to read, even though the compiler accepts them. Each pattern it looks for is called a lint, and each lint has a name such as clippy::needless_range_loop.
Clippy differs from rustc warnings in one way that matters in practice. The compiler's own warnings (unused variables, dead code) come from the compiler. Clippy ships as a separate component and runs on top of the compiler's analysis. It adds several hundred more lints, many of which suggest idiomatic alternatives.
Clippy is also different from rustfmt, which you saw in earlier chapters. rustfmt changes whitespace and layout and never changes what the program does. Clippy reports on the meaning of the code, and some of its fixes change the code's structure.
Running Clippy
Clippy is installed through rustup. Most default toolchains already include it. If the command below fails with "no such command", add the component first.
rustup component add clippyThen run it in a Cargo project like any other Cargo subcommand:
cargo clippycargo clippy first does what cargo check does: it type-checks the crate without producing a binary. It then reports compiler warnings and Clippy lints together. It does not run your program or your tests.
A first finding
Consider this program. It compiles without any compiler warning.
fn main() {
let v = vec![10, 20, 30];
for i in 0..v.len() {
println!("{}", v[i]);
}
}Running cargo clippy reports the clippy::needless_range_loop lint. The index i is used only to read from v, so the loop can iterate over the vector directly. Here is the idiomatic version:
fn main() {
let v = vec![10, 20, 30];
for item in &v {
println!("{item}");
}
}This version has no warning. It also removes a class of mistakes. With manual indexing, a wrong bound such as 0..=v.len() panics at run time. Direct iteration cannot go out of bounds.
Reading a diagnostic
A Clippy diagnostic has the same layout as a compiler diagnostic. For the loop above, the output looks like this (exact wording varies between Clippy versions):
warning: the loop variable `i` is only used to index `v`
--> src/main.rs:3:14
|
3 | for i in 0..v.len() {
| ^^^^^^^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_range_loop
= note: `#[warn(clippy::needless_range_loop)]` on by default
help: consider using an iterator
|
3 | for <item> in &v {
| ~~~~~~ ~~Read it in this order:
- The first line gives the level (
warning) and a short description of the problem. - The
-->line gives the file, line, and column. - The marked code shows exactly which part triggered the lint.
- The
help: for further informationlink opens the lint's documentation page. That page explains why the lint exists, shows an example, and lists known issues. Read it before deciding to ignore a lint. - The
#[warn(clippy::needless_range_loop)]note tells you the lint name and the level it is currently at. You need the name to change its level later. - The final
help:section shows a suggested rewrite.
What Clippy checks
Clippy checks the package you are in. Some options control the scope.
| Command | What it checks |
|---|---|
| `cargo clippy` | The library and binary targets of the current package |
| `cargo clippy --all-targets` | Also tests, examples, and benchmarks |
| `cargo clippy --workspace` | Every package in a Cargo workspace |
| `cargo clippy --all-features` | Code behind every Cargo feature flag |
The default is narrower than many people expect. Code inside #[cfg(test)] modules and files under tests/ is skipped unless you pass --all-targets. A lint in a test helper will therefore stay hidden until you widen the scope. Likewise, code behind a feature that is off by default is never analyzed unless you pass --all-features.
What kinds of problems it finds
Clippy sorts its lints into groups by the kind of problem. The next chapter covers the groups in detail. The examples below show the range of what you will see.
- Correctness. Code that is almost certainly wrong, such as comparing a value to itself (
x == x) orstd::mem::swapon the same variable twice. - Style. Code that works but is not idiomatic, such as
needless_range_loopabove, orif x == true. - Complexity. Code that does something in a harder way than needed, such as
.map(|x| x.clone())where.cloned()would do. - Performance. Code that does avoidable work, such as calling
.expect(&format!(...))so that the string is built even when there is no error. - Suspicious. Code that is probably a mistake but could be intentional.
Here is a short program with two common findings:
fn describe(names: &Vec<String>) -> usize {
let mut count = 0;
for name in names.iter() {
if name.len() > 3 {
count += 1;
}
}
count
}
fn main() {
let names = vec!["Ada".to_string(), "Grace".to_string()];
println!("{}", describe(&names));
}Clippy reports clippy::ptr_arg on the parameter &Vec<String>. A function that only reads the collection should accept &[String], which also accepts a reference to a Vec, an array, or a slice of either. Clippy also notes that names.iter() in a for loop can be written as &names, under the lint clippy::explicit_iter_loop. That lint is part of the pedantic group and is off by default, so you may not see it without enabling it. This is a first example of how the set of lints you see depends on configuration.
A corrected version:
fn describe(names: &[String]) -> usize {
names.iter().filter(|name| name.len() > 3).count()
}
fn main() {
let names = vec!["Ada".to_string(), "Grace".to_string()];
println!("{}", describe(&names));
}The call describe(&names) still compiles, because &Vec<String> coerces to &[String] automatically.
Exit status and warnings
By default, Clippy prints warnings and still exits with status 0. A script that only checks the exit status will not notice them. To make any warning fail the command, pass -D warnings after a -- separator:
cargo clippy --all-targets --all-features -- -D warningsEverything before -- goes to Cargo. Everything after it goes to the Clippy driver, which accepts the same lint flags as rustc. -D warnings means "deny all warnings", which turns every warning into an error. This also includes ordinary compiler warnings, such as unused imports. The CI chapter returns to this command.
Common errors and surprises
A lint disappears after the first run. Cargo caches check results. If you run cargo check and then cargo clippy on unchanged code, Clippy still does its work, because Cargo treats the two as separate. In older toolchains, a cached result could hide warnings, and the fix was to touch a source file or run cargo clean -p <package>. Current toolchains handle this correctly, so if you suspect stale output, update your toolchain before clearing the cache.
Different results on different machines. Clippy is versioned with the Rust toolchain. A newer toolchain adds lints, and a lint that did not exist last month may fail your build today. Pin the toolchain in CI, for example with a rust-toolchain.toml file, if you use -D warnings and want stable results.
Warnings in code you did not write. Clippy does not lint your dependencies. It does lint code produced by your own macros, and in some cases it attributes the warning to a macro call site. If a warning points at a derive or a macro you did not write, check the lint documentation for a known false positive before changing your code.
Treating every suggestion as correct. A lint is a heuristic. Most are reliable, but some have false positives, where the code is fine and the lint is wrong or does not apply. Decide each case on its merit. When you disagree with a lint, silence that one lint on that one item with an attribute, as the lint-levels chapter shows, and add a comment saying why.
The Clippy workflow
In practice, run Clippy often and in small steps. Fixing three warnings after an hour of work is easy. Fixing three hundred when you first add Clippy to an old project is not. If you adopt it late, enable it, record the current number of warnings, and work them down by group.
Summary of commands
# Check the default targets
cargo clippy
# Include tests, examples, benches, and all feature flags
cargo clippy --all-targets --all-features
# Treat every warning as an error (suitable for CI)
cargo clippy --all-targets --all-features -- -D warningsExercise
You run cargo clippy on a crate. It prints no warnings, but your teammate sees a warning in a function inside a #[cfg(test)] module. What is the likely cause, and what command shows the warning?
Show answer
By default cargo clippy checks only the library and binary targets, so code under #[cfg(test)] is not analyzed. Run cargo clippy --all-targets to include tests, examples, and benchmarks.
Exercise
A CI script runs cargo clippy and checks the exit status, but builds never fail even though the log shows Clippy warnings. Why, and how do you fix it?
Show answer
Clippy exits with status 0 when it finds only warnings. Add -- -D warnings so that warnings become errors, for example cargo clippy --all-targets --all-features -- -D warnings.
Exercise
Clippy reports clippy::ptr_arg on fn total(items: &Vec<i32>) -> i32. What parameter type should you use instead, and why does existing code that passes &my_vec still compile?
Show answer
Use &[i32]. A &Vec<i32> coerces to &[i32] automatically, so callers do not need to change, and the function now also accepts arrays and slices.