Skip to content
Tutorials Center
My learning

Topics

Lesson 99 of 132 ยท Testing and Tooling

Clippy, rustfmt and Code Quality

Keep Rust code clean with Clippy lints and before/after fixes, rustfmt, the Cargo lints table, allow and expect, cargo audit and a CI setup.

The Rust compiler is strict about what is wrong. Two official tools go further and tell you what is clumsy: Clippy is a linter with more than seven hundred checks for mistakes, slow patterns and non-idiomatic code, and rustfmt is a formatter that gives every Rust project the same layout. Together they remove most style arguments from code review and catch a surprising number of real bugs.

Both ship with rustup, run through Cargo, and take seconds. This lesson shows what Clippy says about common code (with runnable before and after versions), how to control lints from the source file and from Cargo.toml, how rustfmt decides its layout, and how to put it all in a continuous-integration pipeline. Our editor compiles single files with rustc, so Clippy and rustfmt themselves are shown as read-only terminal sessions, while the code they talk about runs here.

Running Clippy

Clippy is a Cargo subcommand. From a project folder:

Terminal
$ cargo clippy                      # lint the project
$ cargo clippy --all-targets        # include tests, examples, benches
$ cargo clippy --fix                # apply the fixes that are machine-safe
$ cargo clippy -- -D warnings       # turn every warning into an error (CI)

Clippy builds your crate just like cargo check and then runs its own lints on top of the compiler's. The messages look like rustc messages: a lint name, a location and a help: with a suggested replacement.

Lints are sorted into groups, and the group decides whether a lint is on by default:

Group On by default Meaning
clippy::correctness deny (error) Code that is almost certainly wrong
clippy::suspicious warn Code that is probably wrong
clippy::style warn Idiomatic way to write it
clippy::complexity warn Simpler code does the same thing
clippy::perf warn A faster way exists
clippy::pedantic allow Strict, opinionated, some false positives
clippy::restriction allow Bans a feature (such as unwrap); pick lints one by one
clippy::nursery allow New lints still being tested
clippy::cargo allow Cargo.toml hygiene

You do not need to learn the lint names. Read the message, understand the suggestion, and apply it. The pairs below are the ones you will meet in your first week.

Before and after: common Clippy findings

Looping with an index

Here is the shape that people coming from C or Java write by habit.

Rust Index loop that Clippy would flag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Clippy answers with clippy::needless_range_loop: "the loop variable i is only used to index values", and suggests for <item> in values. The idiomatic version avoids bounds checks in the source and cannot go out of range:

Rust The idiomatic version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Both programs print 108. If you really need the index too, use for (i, value) in values.iter().enumerate(). See Iterators.

Parameters: &Vec<T>, &String and &Box<T>

Rust Over-specific parameter types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

&String can only be called with a String, while &str accepts a String, a literal and a slice of either. The same goes for &Vec<T> versus &[T]: an array and a sub-slice work only with the second. Change both parameters to &str and &[i32]; the body does not change, and callers gain flexibility. This is the single most common Clippy finding in beginner code. It is explained from the ownership side in Slices.

Comparing lengths, returning early, matching one case

Several small lints appear together in this function:

Rust Three style lints in one function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The Clippy messages are, in order: length comparison to zero (help: use is_empty), you seem to be trying to use `match` for destructuring a single pattern (help: if let), and unneeded `return` statement (help: remove return and the semicolon). The fixed function:

Rust After applying the suggestions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first return stays: an early exit in the middle of a function is idiomatic, and Clippy flags only a return that is the last expression. Rust functions end with an expression (Syntax).

Needless clones and allocations

The perf and redundant_* lints look for work that costs time for no reason, such as .clone() on a value you never use again, to_string() on something already a String, or vec![] where an array would do:

Rust Needless clones and allocations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The improved version moves name into shout, iterates over [1, 2, 3], and uses sizes.iter().map(|n| n * 2).collect::<Vec<_>>(). Whether Clippy reports each one depends on its version and groups; the habits matter more than the lint names. Allocation costs are covered in Performance and Optimization.

Clippy suggestions are suggestions. A few lints in the pedantic group have false positives, and sometimes a clearer-looking loop is the better code. Understand the reason before you accept or silence a lint.

Lints you can control from the source

Clippy lints and the compiler's own lints (unused_variables, dead_code, unused_must_use, ...) share the same attribute system. Each lint has a level:

Level Effect
allow Do not report it
warn Print a warning, keep compiling
deny Report an error and fail the build
forbid Like deny, and no inner allow can undo it
expect Like allow, but warns if the lint was not triggered (Rust 1.81)

Put the attribute on an item for a local change, or with #![...] at the top of a file or crate for the whole thing. Here deny turns an easily forgotten Result into a hard error:

Rust deny turns a warning into an error (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler stops with error: unused `Result` that must be used, pointing at the fs::write call and noting that this Result may be an Err variant, which should be handled. Without deny it would only be a warning that is easy to ignore.

Now the opposite problem: a lint that is right in general but wrong for one function. Use allow for the narrowest item. Prefer expect, because it complains when the reason disappears:

Rust allow and expect on one item

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first attribute names a Clippy lint: plain rustc ignores unknown tool lints that start with clippy::, so it compiles here and only matters when Clippy runs. #[expect(...)] is satisfied because spare really is unused; remove the variable and the compiler will warn that the expectation is unfulfilled, telling you to delete the attribute. The optional reason documents why.

Configuring lints for a whole project

For project-wide policy, use the [lints] table in Cargo.toml (stable since Rust 1.74). It replaces long lists of #![warn(...)] at the top of main.rs, and workspaces can share one table:

TOML
# Cargo.toml (read-only: needs a Cargo project)
[lints.rust]
unsafe_code = "forbid"
unused_must_use = "deny"

[lints.clippy]
pedantic = { level = "warn", priority = -1 }
unwrap_used = "warn"
dbg_macro = "deny"
module_name_repetitions = "allow"

The priority = -1 makes the whole pedantic group apply first, so the single-lint lines below it can override members of the group. A clippy.toml file in the project root tunes lint thresholds, for example too-many-lines-threshold = 80 or msrv = "1.85" to stop Clippy from suggesting features newer than the oldest compiler you support.

rustfmt: one layout for everyone

rustfmt rewrites source files into the standard style: four spaces, braces on the same line, a trailing comma in multi-line lists, line width up to 100 characters, chains broken one call per line when they do not fit. It does not change meaning, only whitespace, line breaks and trailing commas.

Terminal
$ cargo fmt                 # rewrite all files in place
$ cargo fmt --check         # exit with an error if anything would change (CI)
$ rustfmt src/main.rs       # format a single file

Here are two copies of one program. The first is badly formatted; the second is what cargo fmt produces.

Rust Before rustfmt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust After rustfmt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Both versions print 25 followed by the same list. Notice how rustfmt breaks the long println! and the iterator chain, and puts the closing bracket of the vector on its own line.

Options live in rustfmt.toml (or .rustfmt.toml) in the project root. Keep it nearly empty: the value of rustfmt is that every Rust project looks the same.

TOML
# rustfmt.toml (read-only)
edition = "2024"
max_width = 100        # the default
use_small_heuristics = "Default"

Many options are nightly-only (imports_granularity, group_imports, wrap_comments). If you need to protect a hand-aligned table from reformatting, mark it with #[rustfmt::skip] on the item; use it rarely.

Set your editor to format on save. Then commits contain only real changes, and reviewers never see whitespace diffs.

Supply-chain checks: cargo audit and cargo deny

Quality is also about the code you depend on. Two community tools read Cargo.lock:

Terminal
$ cargo install cargo-audit cargo-deny    # one-time
$ cargo audit                              # known vulnerabilities from the RustSec advisory database
$ cargo deny init && cargo deny check      # advisories, licenses, banned crates, duplicate versions

cargo audit fails when a dependency has a published security advisory. cargo deny adds policy: allow only certain licenses, ban a crate, warn about two versions of the same crate in your tree. You configure it in deny.toml. See Crates and Dependencies for how Cargo resolves versions.

A CI pipeline

Run the same checks on every pull request. A small GitHub Actions workflow is enough (read-only):

YAML
# .github/workflows/ci.yml
name: ci
on: [push, pull_request]
jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: clippy, rustfmt
      - uses: Swatinem/rust-cache@v2
      - run: cargo fmt --all --check
      - run: cargo clippy --all-targets --all-features -- -D warnings
      - run: cargo test --all-features
      - run: cargo audit

Order matters: formatting and Clippy fail fastest, so they run before tests. -D warnings makes any warning (including the compiler's) a failure, which keeps the main branch warning-free. A caveat: when a new Rust release adds a lint, a pinned-stable CI can suddenly fail on old code. Many teams pin the toolchain with a rust-toolchain.toml file and upgrade it deliberately.

TOML
# rust-toolchain.toml (read-only)
[toolchain]
channel = "1.99.1"
components = ["clippy", "rustfmt"]

Habits that keep a codebase clean

  • Run cargo clippy and cargo fmt before every commit, or let a git hook or your editor do it.
  • Fix a warning, do not silence it. If you must allow, do it on the smallest item and say why.
  • Treat unwrap, expect, dbg! and todo! as lints you review (Debugging, Logging and Diagnostics), not as free tools.
  • Start new projects at -D warnings in CI. Adding it to a project with hundreds of warnings is painful.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does cargo clippy -- -D warnings do?

    -D warnings means deny warnings. It is what continuous integration uses to keep the main branch warning-free.
  2. 2. Why does Clippy suggest &[i32] instead of &Vec<i32> for a read-only parameter?

    &Vec<T> dereferences to &[T], so a slice parameter accepts everything the vector parameter did, plus arrays and sub-slices.
  3. 3. What is the benefit of #[expect(lint)] over #[allow(lint)]?

    expect (Rust 1.81) behaves like allow while the lint fires and reports an unfulfilled expectation once it does not.
  4. 4. What does cargo fmt --check do?

    --check is the CI-friendly mode: it exits with a failure and shows a diff when formatting is needed, but never modifies files.
  5. 5. Where do you configure lints for a whole Cargo package without repeating attributes in source files?

    The [lints.rust] and [lints.clippy] tables (stable since 1.74) set levels project-wide and can be shared across a workspace.

Summary

  • Clippy (cargo clippy) finds mistakes and clumsy code; lints are grouped into correctness, suspicious, style, complexity, perf and the opt-in pedantic, restriction, nursery and cargo groups.
  • Common fixes: iterate instead of indexing, take &str and &[T] parameters, use is_empty(), if let for a single pattern, and no return at the end of a function.
  • Lint levels are allow, warn, deny, forbid and expect; set them per item, per crate with #![...], or per project in the [lints] table.
  • rustfmt (cargo fmt, cargo fmt --check) gives every project the same layout; keep rustfmt.toml minimal.
  • cargo audit and cargo deny check dependencies for advisories, licenses and duplicates.
  • In CI run fmt --check, clippy -D warnings, tests and audit, and pin the toolchain when you need stable results.

Next: Performance and Optimization