skip to content

Lints, Formatting and Docs

cargo clippy, cargo fmt and cargo doc run Rust's linter, formatter and documentation generator, and teams wire them into CI. Interviewers ask how lints are configured across a workspace.

on this pageshow

explore

questions

6

In a Rust project's CI job, what do `cargo fmt --check` and `cargo clippy` each verify, and what makes each step fail?

level: juniorimportance: must knowfreq 55%

answer

  1. formatter versus linter
  2. check mode rewrites nothing
  3. a diff and exit status 1
  4. correctness lints are deny
  5. warnings need promoting

basics

~20 s

cargo fmt --check runs rustfmt without rewriting files and fails when any file would change. cargo clippy type-checks the crate and runs Clippy's lints; it fails on deny-level lints, while plain warnings pass unless CI promotes them to errors.

solid answer

~40 s

`cargo fmt` runs rustfmt over every Cargo target in the package (library, binaries, tests, examples and benches) and reads style options from `rustfmt.toml`. With `--check` it changes nothing: it prints a diff of what it would rewrite and exits with status 1, so the step fails until someone runs `cargo fmt` and commits. `cargo clippy` is `cargo check` with Clippy's lints added: it type-checks without generating code and reports lints by group. Lints in `clippy::correctness` are deny-by-default, so `let pi = 3.14;` stops the command with exit status 101; the other default groups only warn, and a warning alone lets the job pass. To fail on every warning, CI sets `CARGO_BUILD_WARNINGS=deny` (Cargo 1.97 and later) or passes `-- -D warnings` to Clippy.

code

console · 14 lines
console
$ cargo fmt --check
Diff in /work/fmtp/src/main.rs:1:
-use std::collections::{HashMap};
+use std::collections::HashMap;
 fn main() {
-    let mut zoom_levels: HashMap<u8,u32> = HashMap::new();
-    zoom_levels.insert(3,64);
-    println!("{:?}",zoom_levels);
+    let mut zoom_levels: HashMap<u8, u32> = HashMap::new();
+    zoom_levels.insert(3, 64);
+    println!("{:?}", zoom_levels);
 }
$ echo $?
1

go deeper

for a junior

Recall that cargo fmt formats and cargo clippy lints, that --check prints a diff and exits 1 without touching files, and that Clippy warnings do not fail a run by default.

for a middle

Explain the default group levels (correctness denied, four groups warning, the rest allowed) and why --all-targets is needed before test code and examples get linted.

for a senior

Show how you make the gate strict without slowing everyone down: deny warnings only in CI through CARGO_BUILD_WARNINGS=deny and run the cheap checks before the tests.

for a principal

Treat formatting and lint gates as team policy: one rustfmt.toml and one lint table for the workspace, so style is argued once in a config review rather than in every pull request.

## Two tools, two different questions A Rust CI pipeline usually runs two cheap checks before the tests. One asks **"is the code formatted the agreed way?"** and the other asks **"does the code pass the linter?"**. Both tools ship with the Rust toolchain as optional rustup components (`rustfmt` and `clippy`), and both are reached through Cargo as `cargo fmt` and `cargo clippy`. The Cargo book lists each as an external command: Cargo finds the `cargo-fmt` or `cargo-clippy` binary and hands the work to it. - **rustfmt** is a *formatter*. It rewrites whitespace, line breaks, import lists and similar layout, and it never changes what the program means. - **Clippy** is a *linter*. It compiles the code far enough to know every type, then reports patterns that are wrong, suspicious, slow or unidiomatic. ## What `cargo fmt --check` does `cargo fmt` formats the root file of every Cargo target in the package and the modules those files pull in: the library, the binaries, integration tests in `tests/`, examples and benches. Style options come from a `rustfmt.toml` (or `.rustfmt.toml`) file, for example `max_width = 80`. An option rustfmt marks unstable is ignored on a stable toolchain, with a warning that unstable features are only available in the nightly channel. With `--check`, rustfmt runs in check mode: 1. It formats each file in memory and compares the result with the file on disk. 2. For every file that would change, it prints `Diff in <path>:<line>:` followed by the removed (`-`) and added (`+`) lines. 3. It leaves every file untouched. 4. It exits with status **1** if any file differs and **0** if none does. So the CI step fails exactly when a commit contains code nobody ran `cargo fmt` on. The fix is local: run `cargo fmt`, commit, push. ## What `cargo clippy` does `cargo clippy` behaves like `cargo check`: it type-checks every selected crate without generating machine code. The difference is the driver. Clippy's driver adds over 800 lints on top of rustc's own, and each Clippy lint belongs to a **group** with a default level: | group | default level | what it catches | |---|---|---| | `clippy::correctness` | deny | code that is outright wrong or useless | | `clippy::suspicious` | warn | code that is most likely wrong | | `clippy::style` | warn | code that could be more idiomatic | | `clippy::complexity` | warn | something simple done in a complex way | | `clippy::perf` | warn | code that could run faster | | `pedantic`, `nursery`, `restriction`, `cargo` | allow | stricter or experimental lints, opt-in only | `clippy::all` is the name for the five groups that are on by default. A **deny** lint is an error. `let pi = 3.14;` triggers `clippy::approx_constant`, Cargo prints `could not compile`, and the exit status is 101. A **warn** lint, such as `clippy::len_zero` for `v.len() == 0`, prints a warning and the command still exits 0. ## When each step fails | step | fails when | exit status | |---|---|---| | `cargo fmt --check` | any file differs from rustfmt's output | 1 | | `cargo clippy` | a deny-level lint or a compile error | 101 | | `cargo clippy` with warnings denied | any lint warning as well | 101 | Because warnings pass by default, most teams promote them in CI. Since **Cargo 1.97** the recommended way is the `build.warnings` setting, usually set only in CI through the environment: `CARGO_BUILD_WARNINGS=deny cargo clippy`. Older pipelines run `cargo clippy -- -D warnings`. The flag goes after `--` because it is meant for Clippy's driver; Cargo itself rejects `cargo clippy -D warnings` with `error: unexpected argument '-D' found`. ## A minimal CI order 1. `cargo fmt --check` takes seconds and catches the most common review nit. 2. `cargo clippy --all-targets` lints tests, examples and benches too, not only the library and binaries. 3. `cargo test` is the slow step, so it runs last. ## Common confusions - `cargo fmt --check` is not a linter. It says nothing about bugs, only about layout. - `cargo clippy` does not replace `cargo test`, because it never runs your tests. - Clippy warnings are advice by default. A pipeline that has not promoted them will merge code that warns. - Cargo caps the lints of non-path dependencies (from a registry or git), so a clean run speaks for your own packages, not for every crate in the dependency graph.

  • Why does a CI job usually run `cargo clippy --all-targets` rather than plain `cargo clippy`?
    Without target flags, `cargo clippy` checks what `cargo check` checks by default: the library and the binaries. Integration tests in `tests/`, examples, benches and `#[cfg(test)]` modules, which only compile in a test build, are skipped. `--all-targets` adds them, so a lint in test code or an example fails the job instead of slipping through.
  • Does `cargo fmt --check` honour the project's `rustfmt.toml`, and what happens to an unstable option on stable Rust?
    Yes. rustfmt reads `rustfmt.toml` or `.rustfmt.toml`, so a setting such as `max_width = 80` changes what counts as formatted for both `cargo fmt` and `--check`. An option rustfmt marks unstable, such as `imports_granularity`, is ignored on a stable toolchain: rustfmt prints a warning that unstable features are only available in the nightly channel and formats with the default.

  • cargo fmt --check reformats the files and then reports success
  • cargo clippy fails the build on every warning by default
  • cargo clippy runs the tests, so a separate cargo test step is redundant
  • Passing -D warnings to cargo clippy before the -- separator works
  • Formatting and linting are the same check, so one of them is enough

Assumes Cargo 1.99; build.warnings (CARGO_BUILD_WARNINGS), the setting that turns lint warnings into a failing command, is stable since Cargo 1.97.

open as a page

With Cargo, what does `cargo doc --no-deps` build, and why does a broken intra-doc link pass `cargo clippy` and `cargo test` unnoticed?

level: middleimportance: should knowfreq 25%

basics

~20 s

cargo doc --no-deps runs rustdoc on the selected packages only and writes HTML to target/doc. Intra-doc links are resolved only by rustdoc, and broken_intra_doc_links only warns, so CI must run cargo doc with that lint denied.

open as a page

In Clippy, which lint groups are off by default, and how should a Rust team adopt the `pedantic` and `restriction` groups?

level: middleimportance: should knowfreq 40%

basics

~20 s

Clippy's pedantic, nursery, restriction and cargo groups are allow-by-default. Teams enable pedantic as a group at a lower priority and allow the lints they reject, but pick restriction lints one at a time, because that group contradicts itself.

open as a page

In Rust 1.81 and later, how does `#[expect(clippy::needless_range_loop)]` differ from `#[allow(clippy::needless_range_loop)]`, and when does it warn?

level: middleimportance: should knowfreq 30%

basics

~20 s

Both silence the named lint, but #[expect] also asserts that the lint fires there. When the code changes and the lint stops firing, rustc warns with unfulfilled_lint_expectations, so a stale suppression surfaces instead of lingering like a forgotten #[allow].

open as a page

In a Cargo workspace, why does `cargo clippy` reject `[workspace.lints.clippy]` setting `pedantic = "warn"` beside `cast_possible_truncation = "allow"`, and how do members inherit it?

level: middleimportance: should knowfreq 40%

basics

~20 s

Cargo ignores the order of keys in a lints table, so a group and a lint at the same priority conflict and Clippy's deny-by-default lint_groups_priority fails the run. Give the group priority = -1, and put lints.workspace = true in every member.

open as a page

After a Rust toolchain bump, CI running `cargo clippy -- -D warnings` fails on code nobody changed; why, and how would you set the warning gate up instead?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Rust releases ship new rustc and Clippy lints and rename or fix old ones, and -D warnings turns every resulting warning into an error. Pin the toolchain, bump it in its own pull request, and deny warnings in CI with CARGO_BUILD_WARNINGS=deny.

open as a page