Sub topic 1
Why Format and Lint: Consistency and Fewer Bugs
Rust's compiler already rejects a lot of broken code. Two other tools ship with the standard toolchain and cover problems the compiler leaves alone. rustfmt rewrites your source files into one standard layout. Clippy reads your code and reports patterns that are probably bugs, slow, or unidiomatic. This chapter explains what each tool is for and where each fits in a project. It also covers what neither tool can do. Later chapters cover commands, configuration, and CI in detail.
Prerequisites
This chapter assumes you can:
- Read and write basic Rust, including functions,
letbindings, loops, and ownership. - Create and build a project with
cargo newandcargo build. - Use a terminal and a code editor.
You do not need any prior experience with rustfmt or Clippy.
Two tools, two different jobs
A formatter changes only how code looks: indentation, spacing, line breaks, and the placement of braces and commas. It never changes what the program does. rustfmt is Rust's official formatter, and you run it through cargo fmt.
A linter analyzes what the code means and reports suspicious or improvable constructs. Each report is called a lint. A lint has a name, such as clippy::needless_range_loop, and a level that decides whether it is ignored, shown as a warning, or treated as an error. Clippy is Rust's official linter, and you run it through cargo clippy.
| Property | rustfmt | Clippy |
|---|---|---|
| Question it answers | Is this code laid out in the standard style? | Is this code likely wrong, slow, or non-idiomatic? |
| Changes program behavior | No | Only if you accept a suggested fix, and then only to correct a problem |
| Judgment involved | Almost none, because the output is deterministic | Some, because lints can be wrong or too strict for your project |
| Typical output | Edited files, or a diff in check mode | Diagnostics with a message, location, and often a suggestion |
| Command | `cargo fmt` | `cargo clippy` |
Both tools are distributed as rustup components, which are optional parts of a toolchain installed by rustup. They are versioned with the compiler, so a newer toolchain can format or lint slightly differently than an older one.
The cost of inconsistent style
Style differences look harmless, but they cost time in a team and in a long-lived codebase.
- Noisy diffs. If one person's editor puts a brace on a new line and another's does not, a small logic change turns into a diff full of whitespace edits. Reviewers have to work out which lines changed meaning.
- Review arguments. Without an automatic standard, code review fills up with comments about spacing and line length. These comments do not improve the program, and they take attention away from design and correctness problems.
- Merge conflicts. Two branches that reformat the same region differently conflict even when neither changed behavior.
- Reading cost. Code in one familiar layout is faster to scan. When every crate you depend on and every project you join looks the same, you spend less effort adjusting.
The community uses the default rustfmt style almost everywhere. Following it means a contributor's first pull request does not start with a style negotiation.
Here is code that compiles and runs but is laid out inconsistently:
fn main(){
let numbers=vec![1,2,3];
let total:i32=numbers.iter().sum();
println!("total = {}",total);
}After cargo fmt, the file contains:
fn main() {
let numbers = vec![1, 2, 3];
let total: i32 = numbers.iter().sum();
println!("total = {}", total);
}The two versions compile to the same program. The only difference is layout, and the formatted version is the one every Rust developer expects.
What a linter catches that the compiler does not
The compiler checks that your program is valid Rust: types match, borrows are sound, and names resolve. It does not check whether valid code does what you meant. Clippy adds more than seven hundred lints for that gap. They fall into a few broad kinds, and the next chapters cover how they are grouped.
- Likely bugs. The code is valid but almost certainly wrong.
- Unidiomatic code. The code works, but a standard library feature expresses the same idea more clearly.
- Performance traps. The code does unnecessary work, such as a needless allocation or clone.
- Complexity. The code is harder to read than it needs to be, for example with too many function arguments.
An example of a likely bug
Floating-point NaN (not a number) is never equal to anything, including itself. This comparison is therefore always false:
fn main() {
let x: f64 = 0.0 / 0.0;
if x == f64::NAN {
println!("x is not a number");
}
}This compiles. The println! never runs, so a check meant to detect NaN silently does nothing. Clippy reports the clippy::cmp_nan lint. That lint is in a group whose default level is deny, so Clippy reports an error rather than a warning. The fix is to ask the value itself:
fn main() {
let x: f64 = 0.0 / 0.0;
if x.is_nan() {
println!("x is not a number");
}
}An example of unidiomatic code
Looping over indexes just to read each element is a habit carried over from other languages:
fn main() {
let v = vec![10, 20, 30];
for i in 0..v.len() {
println!("{}", v[i]);
}
}Clippy reports clippy::needless_range_loop because the index i is used only to read from v. Iterating directly is shorter. It also removes the bounds check on every v[i] access and removes the risk of an off-by-one error in the range:
fn main() {
let v = vec![10, 20, 30];
for item in &v {
println!("{item}");
}
}A Clippy diagnostic has a consistent shape. It names the level and the message, points to the file and line, and often shows a suggested replacement. It ends with a note naming the lint, which you can use to look it up or to configure it later. Reading that lint name is the most useful habit to build early, because every control mechanism in later chapters refers to lints by name.
How the tools fit into a workflow
Format and lint at different moments, each with a different cost of failure.
The order has a reason. Format first so that later diagnostics refer to the final layout of the file. Lint before testing because lints are fast and often point out the cause of a failing test. Run both again in CI because a local habit is not a guarantee. Someone may forget, use an old toolchain, or commit from a machine without an editor setup.
Editors fit in at the first step. With editor integration, formatting runs when you save and Clippy diagnostics appear inline as you type. Most problems are then fixed before you run any command. A later chapter covers this setup.
Installing and checking the tools
If you installed Rust with the default rustup profile, both components are already present. If you used a minimal profile, add them:
rustup component add rustfmt clippy
cargo fmt --version
cargo clippy --versionEach --version command prints a version string tied to the installed toolchain. If a command prints no such command: fmt or no such command: clippy, the component is missing for the active toolchain. Note that components are installed per toolchain, so adding them to stable does not add them to nightly.
Common misconceptions and errors
"A formatter makes my code better." It makes the code consistent, nothing more. It will not fix a confusing name or a wrong algorithm. Its value comes from removing style as a topic of discussion.
"A clean Clippy run means no bugs." Clippy uses pattern matching on the code's structure and types. It finds known bad patterns, not every logic error. Tests, code review, and the type system still carry most of the load.
"Every lint is correct and must be obeyed." Lints are heuristics. Some groups are deliberately opinionated, and a lint can flag code that is right for a specific case. You are expected to read the message, decide, and sometimes allow a lint with a justification. Later chapters show how to do that narrowly, on one item, instead of turning the lint off everywhere.
"Format and lint results are the same on every machine." They depend on the toolchain version. A new Rust release can add lints, which makes a previously clean project print new warnings. It can also adjust rustfmt output slightly. Teams that fail CI on warnings usually pin a toolchain version or accept occasional cleanup after upgrades.
"Linting needs a successful build." Clippy runs the compiler's analysis first, so code that does not compile produces compiler errors rather than lints. Fix compile errors first, then read lints.
Mixing a style change with a logic change. If you adopt rustfmt on an existing unformatted project, run cargo fmt once and commit that change alone. Keeping formatting separate from behavior changes keeps history readable and lets reviewers skip the mechanical commit.
What you will be able to do after this tutorial
The next chapters build on this overview step by step. You will run rustfmt and check formatting without changing files. You will configure rustfmt and exclude code that needs manual layout. You will read Clippy diagnostics, choose among lint groups, and set lint levels with attributes, command-line flags, and the [lints] table in Cargo.toml. You will apply suggested fixes automatically and review them. Finally, you will tune Clippy thresholds, enforce both tools in CI, and set up your editor.
Exercise
A teammate says, "We do not need rustfmt, because Clippy already tells us when code looks wrong." Explain why this is mistaken, naming one thing each tool does that the other does not.
Show answer
The tools answer different questions. rustfmt changes only layout (indentation, spacing, line breaks) and deterministically produces one standard style, which keeps diffs small and removes style arguments from review. Clippy does not reformat files. It analyzes meaning and reports likely bugs and unidiomatic patterns, such as x == f64::NAN or an index-based loop that could iterate directly. Clippy does not enforce a layout, and rustfmt does not detect bugs, so a project benefits from running both.
Exercise
This code compiles. Which Clippy lint would you expect to be reported, and how would you rewrite the loop? fn main() { let names = vec!["ada", "grace"]; for i in 0..names.len() { println!("{}", names[i]); } }
Show answer
Clippy reports clippy::needless_range_loop, because the index i is only used to read from names. Iterate over the vector directly: for name in &names { println!("{name}"); }.