Code Formatting and Linting with rustfmt and clippy

Rust includes built-in tools to keep your code clean, readable, and consistent. Use rustfmt to format code automatically and clippy to catch common mistakes and bad practices. These tools help you write professional-grade code from day one.

Recently, I noticed that all good code looked very similar. That was not an accident, rustfmt and clippy make it easy to stick to Rust’s standards, even if you are new. Think of them like Prettier and ESLint from the JavaScript world, but integrated more deeply.

In this post, I will show you how to use these tools, fix issues, and keep your Rust code clean and idiomatic.

What is rustfmt?

rustfmt is Rust’s official code formatter. It automatically formats your code to follow the standard Rust style guide. You do not have to think about where to put spaces or line breaks: rustfmt does it for you.

Installing rustfmt

It usually comes with Rust, but if not:

rustup component add rustfmt

Using rustfmt

To format a single file:

cargo fmt

To format your whole project:

cargo fmt --all

This will rewrite your files in place. There are no config files needed for basic use.

Example

Before:

fn main(){let x=5;println!("x is {}",x);}

After running cargo fmt:

fn main() {
    let x = 5;
    println!("x is {}", x);
}

Clean, readable, and consistent.

What is clippy?

clippy is a Rust linter. It checks your code for:

  • Unused code
  • Redundant patterns
  • Inefficient expressions
  • Potential bugs
  • Style issues

Installing clippy

If not already available:

rustup component add clippy

Using clippy

To check your project:

cargo clippy

You will get a list of suggestions and warnings:

warning: redundant pattern matching
note: use `if let` instead

Fix the issue and re-run clippy.

Example Clippy Warning

Code:

if x == true {
    do_something();
}

Clippy output:

warning: using `== true` is unnecessary
help: use `if x` instead

Fix:

if x {
    do_something();
}

Clippy helps you learn idiomatic Rust just by reading its suggestions.

Allowing or Denying Lints

If clippy warns about something you do not want to fix yet:

#[allow(clippy::needless_return)]
fn get_number() -> i32 {
    return 5;
}

Or to make it stricter:

#![deny(clippy::all)]

This makes warnings into compile-time errors.

Editor Integration

Most editors (like VS Code with the Rust Analyzer plugin) can run rustfmt and clippy on save. You can turn this on to keep your code clean automatically.

Summary Table

ToolPurposeCommand
rustfmtFormats codecargo fmt
clippyLints and checks for issuescargo clippy