cargo clippy

Learn how to use cargo clippy to find and fix common mistakes in Rust code, integrate it with VS Code, and configure lints for your Axum development environment

cargo clippy is a linter for Rust. A linter is a tool that examines your source code and flags patterns that are likely to be mistakes, overly complex, or not idiomatic Rust. Clippy runs as a separate command on top of the regular Rust compiler, giving you an extra set of warnings that the compiler itself does not produce by default. For an Axum developer, clippy helps you catch subtle issues before they become bugs and teaches you how to write cleaner, more maintainable Rust code.

Why Clippy Exists

The Rust compiler already checks for many errors, but it focuses on whether your code will compile. Clippy goes further and checks how you write the code. It knows hundreds of common patterns that are technically valid but often indicate a misunderstanding or a better alternative. For example, writing if x == true instead of if x compiles fine, but Clippy will warn you because the extra == true is unnecessary and can be simplified. These warnings are not about style preferences - many of them point to real logic problems or performance pitfalls.

Because Rust encourages writing correct code from the start, Clippy acts like a knowledgeable code reviewer that checks every line as you type. It does not change your code automatically, unlike cargo fmt which reformats it. Instead, it gives you descriptions of the problem and often suggests the exact fix you can apply.

How Clippy Fits into Your Workflow

After you have formatted your code with cargo fmt, the next natural step is to run cargo clippy. Clippy will check your code for lints and print any warnings. If there are none, it prints only the usual Checking and Finished lines and returns successfully, with no warnings. This makes it easy to include in your daily routine: after writing or changing code, run cargo clippy before you commit.

Clippy is not a substitute for compilation:

Clippy does not guarantee your code compiles. It runs on the compiler's internal representation, so if your code has a syntax error or type mismatch, Clippy will fail to run at all. Always run cargo check or cargo build to confirm your code compiles, and run Clippy to catch additional issues.

Installing Clippy

Clippy is shipped as a Rust component that you install through rustup. In almost all cases, Clippy is already installed when you install Rust. You can verify by running:

cargo clippy --version

If you see a version number, Clippy is ready. If you get a message that the command is not found, you can install the component with:

rustup component add clippy

This command downloads the Clippy binary for your current toolchain. You only need to run it once per toolchain. Since you are using a stable toolchain for Axum development, this is all you need.

Running Clippy on a Project

Let's create a tiny Rust project to see Clippy in action. Create a new project with Cargo:

cargo new clippy_demo
cd clippy_demo

Open src/main.rs and replace its contents with the following code. This code deliberately contains a common pattern that Clippy will flag.

src/main.rs
fn describe(number: Option<i32>) -> i32 {
    match number {
        Some(value) => value,
        None => 0,
    }
}

fn main() {
    println!("{}", describe(Some(5)));
}

Now run Clippy from the project root:

cargo clippy

You will see output similar to this (the exact wording may vary slightly depending on your Clippy version):

warning: match can be simplified with `.unwrap_or_default()`
 --> src/main.rs:2:5
  |
2 | /     match number {
3 | |         Some(value) => value,
4 | |         None => 0,
5 | |     }
  | |_____^ help: replace it with: `number.unwrap_or_default()`
  |
  = note: `#[warn(clippy::manual_unwrap_or_default)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#manual_unwrap_or_default

The warning tells us several things. The message "match can be simplified with .unwrap_or_default()" explains the issue in plain English. The line number and column point to the exact location. The help: line suggests a replacement: number.unwrap_or_default(). Finally, the note shows the lint name clippy::manual_unwrap_or_default and that it is on by default. If you follow Clippy's advice and change the code to:

src/main.rs
fn describe(number: Option<i32>) -> i32 {
    number.unwrap_or_default()
}

fn main() {
    println!("{}", describe(Some(5)));
}

and run cargo clippy again, you will see no warnings - just the usual Checking and Finished lines. This simple example demonstrates the core workflow: write code, run Clippy, read the warning, apply the suggested fix, and verify the warning disappears.

Understanding Clippy's Output

Clippy's output follows the same format as compiler warnings because Clippy uses the compiler's lint infrastructure. Each warning has:

  • A summary line that describes the problem in human terms.
  • The file and line/column where the issue occurs.
  • A code snippet with a caret pointing to the relevant part.
  • A help: line (often) with a suggested fix that you can copy-paste.
  • The lint name in brackets, like [clippy::manual_unwrap_or_default].
  • An optional note about the default lint level (e.g., "on by default").
  • A link to the Clippy documentation for that lint.

This structure makes it easy to search for a specific lint online or in your editor. In VS Code, these warnings appear as squiggly underlines or in the Problems panel, making them very visible.

Common Clippy Lints for Beginners

Clippy includes hundreds of lints. Here are a few that beginner Rust developers encounter often, with examples of the problem code and the fixed version. Each example is a complete small program you can test yourself.

needless_return

Using return at the end of a function when the value is already the last expression is redundant. Clippy warns about needless_return.

Problem code:

src/main.rs
fn add(a: i32, b: i32) -> i32 {
    return a + b;
}
fn main() {
    println!("{}", add(2, 3));
}

Clippy suggestion: Remove the return keyword and the semicolon.

Fixed code:

src/main.rs
fn add(a: i32, b: i32) -> i32 {
    a + b
}
fn main() {
    println!("{}", add(2, 3));
}

This lint teaches you to use Rust's expression-oriented nature. The last expression in a block is its value; you don't need return unless you are returning early from a loop or a match arm.

redundant_clone

Calling .clone() on a value that is going to be dropped without further use is wasteful. Clippy detects cases where the original value is cloned and then never used again, so the clone could have been a plain move.

Problem code:

src/main.rs
fn call(_s: String) {}

fn main() {
    let x = String::from("hello");
    call(x.clone());
    call(x.clone());
}

Clippy suggestion: The second x.clone() is redundant - by then x is not used for anything else, so you can pass x itself. Note that this lint is in Clippy's nursery group, which is off by default, so you need to enable it explicitly:

cargo clippy -- -W clippy::redundant_clone

That produces warning: redundant clone … help: remove this with the note this value is dropped without further use.

Fixed code:

src/main.rs
fn call(_s: String) {}

fn main() {
    let x = String::from("hello");
    call(x.clone());
    call(x);
}

Note the difference from a needed clone: if the original value is still used afterwards - for example println!("{} {}", s, t) after let t = s.clone(); - the clone is necessary and Clippy stays silent. Pay attention to its suggestion - it often helps you understand Rust's ownership model better.

manual_map

Using a match to transform an Option or Result into another Option or Result can often be replaced with .map() or .and_then(). Clippy suggests manual_map when the pattern is simple.

Problem code:

src/main.rs
fn main() {
    let opt = Some(3);
    let squared = match opt {
        Some(x) => Some(x * x),
        None => None,
    };
    println!("{:?}", squared);
}

Clippy suggestion: Use opt.map(|x| x * x).

Fixed code:

src/main.rs
fn main() {
    let opt = Some(3);
    let squared = opt.map(|x| x * x);
    println!("{:?}", squared);
}

Map chains are more idiomatic and often easier to read once you are comfortable with them. Clippy will gradually introduce you to these combinators.

uninlined_format_args

In recent Rust editions, you can inline simple variable names directly into the format string without using a placeholder and argument list. Clippy can warn when you use println!("{}", x) instead of println!("{x}") - but note that this lint is in the pedantic group, which is off by default, so plain cargo clippy will not flag it. Enable it with:

cargo clippy -- -W clippy::uninlined_format_args

Problem code:

src/main.rs
fn main() {
    let name = "Axum";
    println!("Hello, {}!", name);
}

Clippy suggestion: Use inline format args: println!("Hello, {name}!").

Fixed code:

src/main.rs
fn main() {
    let name = "Axum";
    println!("Hello, {name}!");
}

This lint only applies when the argument is a simple variable name. For complex expressions or formatted output, the old style is still correct.

len_zero

Checking if a collection is empty by comparing its length to zero is less clear than using the is_empty() method. Clippy suggests len_zero for vectors, strings, and other types.

Problem code:

src/main.rs
fn main() {
    let text = String::from("hello");
    if text.len() == 0 {
        println!("empty");
    } else {
        println!("not empty");
    }
}

Clippy suggestion: Use text.is_empty().

Fixed code:

src/main.rs
fn main() {
    let text = String::from("hello");
    if text.is_empty() {
        println!("empty");
    } else {
        println!("not empty");
    }
}

Using is_empty() is more expressive and avoids potential errors when comparing against other lengths.

Configuring Clippy to Match Your Preferences

Not every Clippy warning is appropriate for every project. You might have a legitimate reason to use a pattern that Clippy warns about, or you might want to enforce stricter rules than the defaults. Clippy provides several ways to configure its behavior.

Allowing a lint inline

You can suppress a specific lint for a single item (function, struct, module, etc.) using the #[allow] attribute. For example, if you have an async function that does not need to be async yet, Clippy might warn about unused_async. You can allow it with:

src/main.rs
#[allow(clippy::unused_async)]
async fn maybe_async() {
    // Some placeholder code
}

You can also allow a lint at the crate level by placing #![allow(clippy::lint_name)] at the top of main.rs or lib.rs. This silences the lint for the entire crate.

Denying lints

To treat a Clippy warning as an error, use #[deny(clippy::lint_name)]. This causes the compiler to stop and fail if that lint is triggered. Many projects use #![deny(clippy::all)] at the crate root to enforce all default Clippy lints as errors. However, this can be too strict for beginners; it's often better to start with warnings and gradually promote lints to errors once your code is clean.

The clippy.toml file

Some lints accept configuration values. Clippy looks for a clippy.toml file in the project root or in any parent directory. For example, the too_many_arguments lint defaults to flagging functions with more than 7 arguments. You can change that threshold:

clippy.toml
too-many-arguments-threshold = 10

This file uses TOML syntax, just like Cargo.toml. Not all lints have configuration options; consult the Clippy documentation for details.

Command line flags

You can override lint levels directly when running Clippy:

# Allow a specific lint
cargo clippy -- -A clippy::some_lint
# Deny a specific lint (treat as error)
cargo clippy -- -D clippy::some_lint
# Warn about a lint that is off by default
cargo clippy -- -W clippy::some_lint

The -- separates Cargo's arguments from Clippy's arguments. You can also combine multiple flags. For example, to deny all warnings and turn one back into a warning:

cargo clippy -- -D warnings -A clippy::too_many_arguments

Checking all targets and features

By default, Clippy checks only the default target (usually the binary or library). To include tests, benchmarks, and examples, use:

cargo clippy --all-targets --all-features

This is useful for catching lints in test code and integration tests. In CI environments, this command is often paired with -- -D warnings to fail the build on any lint.

Be careful with -D warnings in existing projects:

If you add -D warnings to a project that already has many Clippy warnings, the build will fail immediately. Before enforcing warnings as errors, run cargo clippy normally and fix all warnings, or use #[allow] selectively for lints you intentionally ignore.

Using Clippy with VS Code

Because you are setting up your development environment in VS Code, you will likely want Clippy warnings to appear directly in the editor as you type. The rust-analyzer extension supports running Clippy on save, which gives you real-time feedback.

By default, rust-analyzer runs cargo check when you save a file. You can change it to run clippy instead, which provides all the default compiler checks plus Clippy lints.

Open your VS Code settings (File > Preferences > Settings, or Ctrl+,). Search for "rust-analyzer check command" and set it to clippy. Alternatively, edit your settings.json file (User or Workspace) and add:

settings.json
{
  "rust-analyzer.checkOnSave": true,
  "rust-analyzer.check.command": "clippy"
}

rust-analyzer.checkOnSave is the on/off switch (a boolean, default true); rust-analyzer.check.command is the command to run (default "check", set to "clippy" here). Do not use the older nested key rust-analyzer.checkOnSave.command - it is deprecated.

After saving these settings, rust-analyzer will run Clippy every time you save a Rust file. Warnings appear as yellow squiggles in the editor, and you can hover over them to see the full Clippy message and suggested fix. Additionally, the Problems panel (Ctrl+Shift+M) lists all Clippy warnings in the workspace.

For quick fixes, place your cursor on a warning and press Ctrl+. (or right-click and select "Quick Fix"). VS Code will show the Clippy suggestion, and you can apply it with a click. This makes fixing lints extremely fast.

Confirm Clippy is working in VS Code:

After configuring rust-analyzer to use Clippy, save a file that contains a known Clippy warning (like the manual_unwrap_or_default example from earlier). If you see a yellow underline and a message mentioning clippy::manual_unwrap_or_default, your integration is working correctly.

Running Clippy on Dependencies and in CI

When you run cargo clippy without arguments, it checks only your own crates - the packages in your workspace. Your dependencies are compiled so your code can be checked, but Clippy does not lint them: their lints are capped, so warnings in other people's code never show up in your output. You cannot make Clippy lint a dependency by dropping a flag; there is no flag for it.

The --no-deps flag makes that default explicit for the current package:

cargo clippy --no-deps

It restricts the run to the package in the current directory, without linting the other members of your workspace. For most Axum development, plain cargo clippy is what you want.

For CI (continuous integration), you might add a step that runs:

cargo clippy --all-targets --all-features -- -D warnings

This ensures that any new Clippy warning breaks the build, preventing lint issues from accumulating. You can add this to a GitHub Actions workflow or your preferred CI system.

Common Mistakes and Misconceptions

Clippy warnings are not always errors

A Clippy warning is a suggestion, not a compiler error. Your code will still compile if you ignore a warning. However, many warnings point to real bugs or inefficiencies, so it's a good habit to address them promptly.

Overusing #[allow] without understanding

When you see a Clippy warning, the first reaction should be to understand why it appears. If you then decide the pattern is intentional, add a targeted #[allow] with a comment explaining why. Avoid sprinkling #[allow] on every function just to silence warnings; that hides potential problems.

Not knowing that Clippy does not modify code

Clippy only reports problems; it does not fix them automatically. Some tools or editor actions can apply the suggested fixes, but Clippy itself is read-only. This is different from cargo fmt, which rewrites your file. Keep that in mind.

Confusing Clippy with the Rust compiler's built-in lints

Rust has its own set of lints (dead_code, unused_variables, etc.) that are controlled with #[allow(dead_code)] and similar. Clippy adds many more lints under the clippy:: prefix. Both can appear as warnings, but they come from different sources. You can configure both separately.

Do not ignore Clippy warnings in code you plan to share:

When you contribute to open-source projects or share your Axum code with others, maintainers often run Clippy as part of their review process. A pull request with many Clippy warnings may be rejected. Run cargo clippy before submitting your code to avoid surprises.

Summary

Clippy is an extra set of eyes that helps you write better Rust code. It catches many common mistakes, suggests more idiomatic alternatives, and teaches you the language's best practices. By integrating Clippy into your VS Code setup, you get immediate feedback every time you save a file, making it painless to keep your Axum project clean. Once you are comfortable running Clippy manually and seeing its warnings in your editor, the next tool to explore is cargo-watch, which automatically re-runs Clippy or other commands whenever you modify a file, further streamlining your development loop.