Sub topic 1
Why Format and Lint Rust Code with rustfmt and Clippy
Prerequisites
This chapter assumes basic Rust syntax, ownership, Cargo commands, a terminal, and a code editor.
Why Format and Lint
Formatting makes source code follow one shared layout. rustfmt is Rust's standard formatter. It changes whitespace and line breaks without changing the program's intended behavior.
Linting checks source code for patterns that may indicate bugs or unclear design. Clippy is Rust's collection of lints. It can suggest simpler, safer, or more idiomatic code.
Together, these tools reduce review noise. A formatter handles style automatically, while Clippy draws attention to code that deserves a decision.
Formatting Code with `cargo fmt`
Cargo provides the usual interface for rustfmt. Run this command from a project directory:
cargo fmtIt formats Rust files in place. To check formatting without changing files, use:
cargo fmt --all -- --checkThe check exits unsuccessfully when a file differs from rustfmt's result. This makes it useful in continuous integration, where unformatted code should fail the job.
Configuring rustfmt
Place project-wide settings in a file named rustfmt.toml at the project root:
max_width = 100
edition = "2021"
use_field_init_shorthand = trueUse stable options when possible. The edition setting tells rustfmt which Rust edition the code uses. max_width controls preferred line length. Configuration should support readability rather than force unusual layouts.
Opting Out of Formatting for Specific Items
Most code should use the standard formatter. For a deliberately aligned item, add #[rustfmt::skip]:
#[rustfmt::skip]
const IDENTITY: [[u8; 3]; 3] = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
];This attribute prevents rustfmt from rewriting that item. Use it sparingly. Skipping formatting creates a manual maintenance obligation and can hide later changes from the normal style check.
Exercise
Which command checks formatting without modifying files?
Show answer
cargo fmt --all -- --check.