How to Use cargo clippy for Linting in Rust

Run `cargo clippy` in your project root to analyze your code for common mistakes, performance issues, and style violations that the compiler misses.

Run cargo clippy in your project root to analyze your code for common mistakes, performance issues, and style violations that the compiler misses. It integrates directly with your build system, so you can treat warnings as errors in CI/CD pipelines to enforce code quality standards.

Here is the basic command to run Clippy on your current workspace:

cargo clippy

If you want to enforce strict standards by treating all Clippy warnings as build-breaking errors, use the -- -D warnings flag. This is essential for CI environments to prevent bad code from merging:

cargo clippy -- -D warnings

You can also configure Clippy behavior via your Cargo.toml to suppress specific lints or enable pedantic checks. Add a [lints] section to your Cargo.toml to enable the "pedantic" category, which includes many additional style and correctness checks:

[lints.rust]
unsafe_code = "forbid"

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

Clippy runs as a separate tool that hooks into the compilation process, so it doesn't require a separate build step. It reads your code, applies its rules, and outputs warnings similar to rustc. If you need to fix issues automatically, combine it with cargo fix:

cargo clippy --fix --allow-dirty

Note that --fix requires the --allow-dirty flag if you have uncommitted changes, as Clippy modifies source files directly. Always review the changes before committing. For continuous integration, simply add cargo clippy -- -D warnings to your workflow YAML or shell script. This ensures that any new code introduced into the repository adheres to your team's quality guidelines without manual intervention.