Sub topic 13
Formatting and linting with cargo fmt and cargo clippy
This chapter assumes you have installed Rust with rustup, can create a project with cargo new, and can run cargo build and cargo run. It covers the two tools that keep a Rust codebase tidy: rustfmt for layout and Clippy for code quality.
Two tools, two jobs
rustfmt rewrites your source files into the standard Rust style. Clippy is a linter, which means it reads your code and reports patterns that are likely to be bugs, slow, or unidiomatic. Both ship as rustup components and are run through Cargo subcommands.
| Tool | Command | What it does |
|---|---|---|
| rustfmt | `cargo fmt` | Rewrites files to the standard style |
| Clippy | `cargo clippy` | Reports warnings and suggestions |
Making sure the components are installed
The default rustup profile usually includes both components. If a command says it is not found, add them:
rustup component add clippy rustfmtComponents belong to a toolchain. If you install a new toolchain later, add them again for that toolchain.
Formatting with cargo fmt
Create a project and write some badly formatted code in src/main.rs:
fn main(){
let numbers=vec![1,2,3];
let total:i32=numbers.iter().sum();
println!("total = {}",total);
}Run the formatter from the project directory:
cargo fmtThe file is rewritten in place:
fn main() {
let numbers = vec![1, 2, 3];
let total: i32 = numbers.iter().sum();
println!("total = {}", total);
}To check formatting without changing any files, which is useful in automated checks, use:
cargo fmt --checkThis prints a diff of what would change and exits with a non-zero status if any file is not formatted.
Linting with cargo clippy
Clippy compiles your project and adds its own checks. Replace src/main.rs with code that is valid but not idiomatic:
fn main() {
let names = vec!["Ada", "Grace"];
let count = names.len();
if count == 0 {
println!("empty");
}
for i in 0..names.len() {
println!("{}", names[i]);
}
}Then run:
cargo clippyClippy warns about the loop that indexes with 0..names.len(). It suggests iterating over the items directly, and it often shows the replacement code. A cleaner version looks like this:
fn main() {
let names = vec!["Ada", "Grace"];
if names.is_empty() {
println!("empty");
}
for name in &names {
println!("{name}");
}
}Clippy also reports ordinary compiler warnings, so one command covers both.
How the tools fit the workflow
A common habit is to run cargo fmt before each commit, and to run cargo clippy whenever cargo check passes.
Treating warnings as errors
By default Clippy prints warnings and still succeeds. In automated checks you often want the build to fail instead. Pass -D warnings after --:
cargo clippy -- -D warningsEverything after -- goes to Clippy itself, and -D warnings means "deny warnings", so any warning becomes an error.
Common mistakes
- Running
cargo fmton a project with unsaved editor changes. The formatter works on files on disk, so save first. - Expecting
cargo fmtto catch logic problems. It only changes layout. Use Clippy for that. - Ignoring a Clippy warning without reading it. The message usually explains why the pattern is a problem.
- Forgetting that components are per toolchain after switching channels.
Exercise
Exercise
You want a script that fails if any file is not formatted and also fails on any Clippy warning, without modifying files. Which two commands do you run?
Show answer
cargo fmt --check and cargo clippy -- -D warnings. The first reports unformatted files through its exit status without rewriting them. The second turns every Clippy warning into an error.
Exercise
After running rustup toolchain install beta, cargo +beta clippy reports that Clippy is not installed. What do you do?
Show answer
Add the component to that toolchain, for example with rustup component add clippy --toolchain beta, because components are installed per toolchain.