Sub topic 2
Finding Problems with `cargo clippy`
Assume you know basic Rust syntax, ownership, Cargo projects, and terminal commands. Clippy is Rust’s linter: a tool that analyzes code and reports likely bugs, inefficient patterns, and code that is harder to read than necessary.
Running Clippy
Run Clippy from the directory containing Cargo.toml:
cargo clippyFor a project with tests, examples, binaries, and optional features, use:
cargo clippy --all-targets --all-featuresClippy prints a diagnostic with the lint name, source location, explanation, and often a suggested fix.
This example uses an index only to read vector elements:
fn main() {
let values = vec![10, 20, 30];
for index in 0..values.len() {
println!("{}", values[index]);
}
}Clippy can report clippy::needless_range_loop. Iterating over the values directly expresses the intent more clearly:
fn main() {
let values = vec![10, 20, 30];
for value in &values {
println!("{value}");
}
}A lint is a named rule that detects a pattern. Clippy does not prove that your program is correct. Review each suggestion against the program’s behavior.
Understanding Clippy Lint Groups
Clippy organizes related lints into groups. Common groups include:
| Group | Purpose |
|---|---|
| `clippy::all` | The main collection of Clippy lints |
| `clippy::pedantic` | Stricter style and correctness suggestions |
| `clippy::nursery` | Experimental lints that may change |
| `clippy::restriction` | Highly opinionated rules; enable selectively |
A group lets you configure many lints at once. pedantic may improve consistency, but it can also produce suggestions that do not fit every project. Start with clippy::all, then add stricter groups deliberately.
Controlling Lint Levels
Each lint has a level:
allowignores the lint.warnreports it but permits compilation.denytreats it as a compilation error.forbidtreats it as an error and prevents later overrides.
Use a command-line flag for a one-time or CI policy:
cargo clippy --all-targets --all-features -- -D warningsUse an attribute for a local exception:
#[allow(clippy::too_many_arguments)]
fn draw(x: i32, y: i32, width: i32, height: i32, r: u8, g: u8, b: u8, a: u8) {
let _ = (x, y, width, height, r, g, b, a);
}Keep exceptions narrow. Suppressing one lint on one function preserves useful diagnostics elsewhere.
Exercise
Which command makes every Clippy warning fail the build?
Show answer
cargo clippy --all-targets --all-features -- -D warnings.