Clippy is a «collection of lints to catch common mistakes and improve your Rust code». 💪
But for some reason Clippy looks like a hidden treasure inside the cargo
command. I found this by accident checking the code of the Orogene tool.
How can I get clippy?
Now, Clippy is inside cargo
but is not listed when you run the cargo --help
command. The same happens with cargo fmt
to format your code, maybe there are more easter eggs inside cargo
.
Also, there is a guide about how to add clippy
to cargo if this is not present in your CLI.
And what does clippy do?
As any linters, clippy has a list of warnings like manual_memcpy:
What it does
Checks for for-loops that manually copy items between slices that could be optimized by having a memcpy.
Why is this bad
It is not as fast as a memcpy.
Example
for i in 0..src.len() {
dst[i + 64] = src[i];
}
Could be written as:
dst[64..(src.len() + 64)].clone_from_slice(&src[..]);
And a long list of lint errors here.
How to run this command?
Clippy builds your code and then runs the linter, so Clippy receives the same arguments as the cargo check
subcommand.
cargo clippy # Run in the default package(s).
cargo clippy --release # Run in release mode
cargo clippy --workspace # Checks the packages in the monorepo
cargo build --package myPkgName # An specific page
Then, after the --
you can add the arguments for clippy itself:
RUSTFLAGS="-Dwarnings" cargo clippy -- -D warnings
With this argument the build job will fail when encountering warnings. The RUSTFLAGS="-Dwarnings"
environment variable is required to get this effect but the README doesn't mention it.
The custom configuration
You can configure the lint rules in a file called clippy.toml
, e.g. you can turn the pedantic
rules:
#![deny(clippy::pedantic)]
These rules contain some very aggressive lints prone to false positives. 🤭
You can check more examples here.
The CI config
The best config for CI is checking the code format, then linting in the code behavior, and finally running the tests that you wrote:
# set env RUSTFLAGS="-Dwarnings"
cargo fmt --workspace -- --check
cargo clippy --workspace -- -D warnings
cargo test --workspace
That's all! And... Isn't it awesome?
To spend a minute and use a lint tool, in my opinion, is one of those things that marks a difference and makes your code professional, clean and performant.
If you don't use them, I encourage you to start now! There are a lot of basic guides out there.
If you love to use them, now you know a hidden new trick (feels good, right?)
Tell me what you think!
Have you ever found or implement useful tools in Rust? 🦀 Have you improved your code with Clippy?
Tell me about it in the comments!
Top comments (3)
Thx man! This would make a great VS code extension.
This got my attention. I was planning to learn Go but I really liked that inline 'for-ish' thing
It's cool to know this!! +1