Sub topic 13
Formatting and linting with cargo fmt and cargo clippy
This chapter assumes you can run shell commands, have installed Rust with rustup, and can create and build a project with cargo new and cargo build. It covers the two tools most Rust projects run before every commit: rustfmt, which formats code, and Clippy, which lints it.
Formatter versus linter
A formatter rewrites whitespace, line breaks, and layout. It never changes what the program does. A linter reads the code and reports patterns that are likely to be bugs, slow, or unidiomatic. Some lint findings can be fixed automatically. Others need your judgment.
| Tool | Cargo command | What it does | Changes behavior? |
|---|---|---|---|
| rustfmt | `cargo fmt` | Rewrites source files to the standard style | No |
| Clippy | `cargo clippy` | Reports suspicious or non-idiomatic code | Only if you apply a fix |
Both tools are rustup components. They are separate from rustc and Cargo, so a minimal toolchain may not include them.
Installing the components
The default rustup profile usually installs both tools. If cargo fmt or cargo clippy reports that the command is missing, add the components:
rustup component add clippy rustfmt
rustup component list --installedComponents belong to a toolchain. If you install a new toolchain later, such as nightly, add the components to that toolchain too:
rustup component add clippy rustfmt --toolchain nightlyFormatting with cargo fmt
Create a project with deliberately messy code to see the formatter work:
cargo new lint_demo
cd lint_demoReplace src/main.rs with this:
fn main(){
let numbers=vec![1,2,3,4,5];
let mut total=0;
for n in numbers.iter(){
total+=n;
}
println!("total = {}",total);
}Run the formatter:
cargo fmtcargo fmt rewrites every Rust file in the package in place. Afterward, src/main.rs looks like this:
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let mut total = 0;
for n in numbers.iter() {
total += n;
}
println!("total = {}", total);
}The output is the standard Rust style: four-space indentation, spaces around operators, and a space before the opening brace. Because nearly every Rust project uses this style, code from any crate looks familiar, and style arguments in code review disappear.
Checking without rewriting
In continuous integration (CI), you usually want to fail the build when code is unformatted instead of changing files. Use the --check flag:
cargo fmt --checkWith --check, rustfmt prints a diff of the changes it would make and exits with a non-zero status if any file differs. It writes nothing. This makes it suitable for a CI step or a Git pre-commit hook.
Configuring rustfmt
rustfmt works with no configuration, and most teams leave it that way. If you need to change a setting, create a rustfmt.toml (or .rustfmt.toml) file in the project root:
max_width = 100
use_small_heuristics = "Max"max_width sets the maximum line length. The default is 100, so the value above is shown only as an example of the syntax. Many options are unstable and work only on the nightly toolchain. If a stable build prints a warning that an option is unstable, remove that option or accept that your team needs nightly formatting.
Skipping code
Occasionally a hand-formatted block, such as a lookup table, reads better than the formatter's output. Mark it with the #[rustfmt::skip] attribute:
#[rustfmt::skip]
const IDENTITY: [[i32; 3]; 3] = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
];
fn main() {
println!("{:?}", IDENTITY);
}Use this sparingly. Each skipped block is code that the formatter no longer protects.
Linting with cargo clippy
Clippy contains several hundred lints. They are grouped by how confident the Clippy team is that a finding is a real problem.
| Lint group | Default level | Meaning |
|---|---|---|
| `clippy::correctness` | deny (error) | Code that is almost certainly wrong |
| `clippy::suspicious` | warn | Code that is probably wrong |
| `clippy::style` | warn | Code that works but is not idiomatic |
| `clippy::complexity` | warn | Code that does something simple in a complicated way |
| `clippy::perf` | warn | Code that could run faster |
| `clippy::pedantic` | allow (off) | Stricter, opinionated lints |
| `clippy::nursery` | allow (off) | New lints still under development |
Run Clippy in the same way you run cargo check:
cargo clippyClippy first type-checks the project, as cargo check does, and then runs its lints on top. It does not produce a binary.
Reading a finding
Put this code in src/main.rs:
fn main() {
let names = vec!["ada", "grace", "linus"];
let count = names.len();
if count == 0 {
println!("no names");
}
let mut longest = String::new();
for name in names.iter() {
if name.len() > longest.len() {
longest = name.to_string();
}
}
let total: i32 = vec![1, 2, 3].iter().map(|x| *x).sum();
println!("{longest} {total}");
}Running cargo clippy reports warnings similar to the following. The exact wording differs between Clippy versions.
warning: length comparison to zero
--> src/main.rs:5:8
|
5 | if count == 0 {
| ^^^^^^^^^^ help: using `is_empty` is clearer and more idiomatic
warning: useless use of `vec!`
--> src/main.rs:14:22
|
14 | let total: i32 = vec![1, 2, 3].iter().map(|x| *x).sum();
| ^^^^^^^^^^^^^ help: you can use an array directly: `[1, 2, 3]`Each finding has four parts: the severity (warning or error), a short description, the location, and a help line with a suggested rewrite. The text also names the lint, for example clippy::len_zero, and a link to its documentation. Read that documentation before changing code. It explains why the pattern is flagged and shows an example of the preferred form.
Applying fixes automatically
Many Clippy lints carry a machine-applicable fix. Apply them with:
cargo clippy --fixCargo refuses to run --fix when your working tree has uncommitted changes, because it cannot tell its edits from yours. Commit or stash first, or pass --allow-dirty to override the check. Review the result with git diff afterward. Automatic fixes are mechanical, and you remain responsible for confirming the program still does what you intended. Fixes that are not machine-applicable are left alone, and Clippy reports them as before.
Controlling lints
Turning warnings into errors
In CI, you normally want warnings to fail the build. Pass -D warnings to the lint driver after --:
cargo clippy -- -D warningsArguments before -- go to Cargo. Arguments after it go to Clippy and rustc. -D means deny, so every warning becomes an error and the command exits with a non-zero status.
A common CI sequence checks both tools:
cargo fmt --check
cargo clippy --all-targets -- -D warnings
cargo testThe --all-targets flag makes Clippy lint tests, examples, and benchmarks as well as the main code. Without it, Clippy checks only the library and binary targets.
Allowing or denying specific lints
You can adjust a single lint with an attribute. Put it on an item to scope it to that item, or at the top of a crate root with #![...] to cover the whole crate:
#![warn(clippy::pedantic)]
#[allow(clippy::needless_range_loop)]
fn sum_first_three(values: &[i32]) -> i32 {
let mut total = 0;
for i in 0..3 {
total += values[i];
}
total
}
fn main() {
println!("{}", sum_first_three(&[10, 20, 30, 40]));
}Here the crate opts into the stricter pedantic group, and one function opts out of a single lint. Prefer the narrowest scope that works. A crate-wide allow hides the same finding in code you write later.
Since Rust 1.74, you can also set lint levels for a whole package in Cargo.toml:
[lints.clippy]
pedantic = { level = "warn", priority = -1 }
needless_range_loop = "allow"The priority = -1 entry on the group lets the individual lint on the next line override it. Without the lower priority, the order of group and single-lint settings would not behave as you expect. A [lints] table is easier to review than attributes scattered across files, and it applies to every target in the package.
Using expect
When you silence a lint, consider #[expect(...)] instead of #[allow(...)]:
#[expect(clippy::needless_range_loop)]
fn first(values: &[i32]) -> i32 {
let mut result = 0;
for i in 0..1 {
result += values[i];
}
result
}
fn main() {
println!("{}", first(&[7, 8, 9]));
}#[expect] behaves like allow, but the compiler warns if the lint no longer fires. That makes stale suppressions visible. It requires Rust 1.81 or later.
Where the tools fit in the workflow
The tools form a loop around the build and test commands you already know.
Run cargo fmt first so that lint output and diffs are not cluttered by layout noise. Run Clippy before tests because it is faster than a full test run and catches many mistakes early.
Common problems
error: 'cargo-clippy' is not installed for the toolchain: The component is missing for the active toolchain. Runrustup component add clippy.cargo fmtchanges files you did not touch: Another contributor used a different rustfmt version or a differentrustfmt.toml. Pin the toolchain with arust-toolchain.tomlfile so everyone formats with the same version.- Clippy reports nothing after you edit code: Cargo caches results. If a file is unchanged, Clippy does not re-run on it. Touch the file or run
cargo clean -p your_packageto force a fresh run. - Formatting differs between stable and nightly: Nightly accepts unstable options and can format some constructs differently. Use one toolchain for the formatting check in CI.
- A lint seems wrong for your case: Treat Clippy as advice. Suppress a lint with a scoped
alloworexpectand a comment explaining why, rather than contorting the code.
Pinning the toolchain for a team
A rust-toolchain.toml file in the project root makes rustup select a specific toolchain and components when anyone runs Cargo inside the directory:
[toolchain]
channel = "stable"
components = ["clippy", "rustfmt"]With this file in place, rustup installs the listed components automatically if they are missing. Replacing "stable" with a specific version, such as "1.82.0", makes formatting and lint results identical across machines until you change the file.
Exercise
Your CI job must fail if any file is unformatted or if Clippy reports any warning, including warnings in test code. Write the two commands, and explain why cargo fmt --check is used instead of cargo fmt in this job.
Show answer
Use cargo fmt --check and cargo clippy --all-targets -- -D warnings. cargo fmt --check prints a diff and exits with a non-zero status without modifying files, so CI fails on unformatted code. Plain cargo fmt would rewrite the files inside the CI runner, exit successfully, and hide the problem. --all-targets extends Clippy to tests, examples, and benchmarks, and -D warnings turns every warning into an error.
Exercise
You want Clippy's pedantic group enabled for a whole package, except for the lint needless_range_loop, which you want off. Show the Cargo.toml configuration and explain why the group needs a priority value.
Show answer
Add this table:
[lints.clippy]
pedantic = { level = "warn", priority = -1 }
needlessrangeloop = "allow"
Cargo applies lint settings in order of priority, and entries with the same priority can conflict in ways that depend on ordering. Giving the group priority = -1 makes it lower than the default of 0, so the single-lint setting is applied afterward and wins over the group setting.