Rust Clippy and Rustfmt

Good code needs consistent style and few avoidable mistakes. Two official tools help with both. Rustfmt arranges code into one standard layout, and Clippy reviews code for common errors and clumsy patterns. Imagine a proofreader who fixes spacing and punctuation, paired with an editor who suggests clearer wording.

Installing the Tools

Both tools ship with the default Rust installation. If a component is missing, add it with rustup.

rustup component add rustfmt
rustup component add clippy

Rustfmt: One Style for Everyone

Teams waste time debating where braces belong and how long a line may run. Rustfmt ends the debate by applying one community style to every file.

Running Rustfmt

cargo fmt

The command rewrites every source file in the project. Add -- --check to report differences without changing files.

Before and After

fn   add(a:i32,b:i32)->i32{
let sum=a+b;
sum}
fn add(a: i32, b: i32) -> i32 {
    let sum = a + b;
    sum
}
 messy code --> [ cargo fmt ] --> clean, uniform code

Adjusting Settings

A file named rustfmt.toml in the project root changes the defaults.

max_width = 100
tab_spaces = 4

Most teams keep the defaults, because shared style is the whole purpose of the tool.

Protecting a Region

The attribute #[rustfmt::skip] keeps a hand-aligned block exactly as written, such as a table of numbers.

#[rustfmt::skip]
let matrix = [
    1, 0, 0,
    0, 1, 0,
    0, 0, 1,
];

Clippy: A Code Reviewer

Clippy contains hundreds of checks called lints. Each lint spots a pattern that is wrong, slow, confusing, or less idiomatic than a known alternative.

cargo clippy

A Typical Warning

fn main() {
    let items = vec![1, 2, 3];
    if items.len() == 0 {
        println!("empty");
    }
}
warning: length comparison to zero
  --> src/main.rs:3:8
   |
 3 |     if items.len() == 0 {
   |        ^^^^^^^^^^^^^^^^ help: using `is_empty` is clearer: `items.is_empty()`

The suggested version reads like plain English and works for every collection.

if items.is_empty() {
    println!("empty");
}

More Patterns Clippy Catches

Pattern in CodeClippy Advice
return value; as the last lineRemove the needless return
Cloning a value that implements CopyDrop the clone call
Comparing a bool to trueUse the bool directly
A manual loop that copies itemsUse an iterator method
Passing &Vec to a functionAccept &[T] instead

Automatic Fixes

Many suggestions apply themselves. Commit your work, run the fixer, and review the changes.

cargo clippy --fix

Lint Levels

Each lint carries a level: allow, warn, or deny. Attributes change the level for a function, module, or whole crate.

#[allow(clippy::too_many_arguments)]
fn build(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32, h: i32) {}

// Stop the build on any warning:
#![deny(warnings)]

Use allow rarely, and add a comment that explains the reason.

Lint Categories

  • correctness flags code that is almost certainly wrong.
  • style flags code that works yet breaks community habits.
  • complexity flags code that has a simpler form.
  • perf flags code that wastes time or memory.
  • pedantic offers stricter opinions and stays off by default.

Using Both in a Workflow

 write code
     |
     v
 cargo fmt     (style)
     |
     v
 cargo clippy  (quality)
     |
     v
 cargo test    (behavior)
     |
     v
 commit

Teams run these commands in automated checks, so every change meets the same standard before it joins the main project.

cargo fmt -- --check
cargo clippy -- -D warnings
cargo test

The option -D warnings turns every Clippy warning into an error, which makes the check strict.

Learning from Clippy

Treat each warning as a short lesson. The messages explain the reason behind the advice and link to the full lint description. Many beginners improve quickly by reading and applying them.

Editor Support

Popular editors run both tools automatically. Rust Analyzer can format code on save and display Clippy hints beside the affected lines. The setup gives instant feedback while you type, so style problems never pile up.

Key Points

  • cargo fmt applies one standard layout to your code.
  • cargo clippy reports mistakes and suggests cleaner patterns.
  • cargo clippy --fix applies safe suggestions automatically.
  • Run both tools together with tests before sharing code.