Overview
rustfmt is Rust's answer to the formatting question, run as cargo fmt and installed
as a rustup component. The culture is gofmt-shaped — format on save, check in CI, never
argue in review — but the tool itself sits one notch less absolutist than
gofmt: a rustfmt.toml exists and can change
real decisions. The idiomatic position is to not have one, or to keep it to one or two
lines; a long rustfmt.toml is a team smell.
Key points
cargo fmtformats the whole workspace;cargo fmt --checkis the CI gate (non-zero exit + diff on stdout).- Default style is the Rust Style Guide — since the 2024 edition work, the style
guide is versioned with editions (
style_edition), so defaults can evolve without reformatting old code under old editions. - Configuration exists but is culturally discouraged:
max_width(default 100),use_small_heuristics, import granularity — the useful stable knobs roughly end there. - The good knobs are still unstable:
group_imports = "StdExternalCrate",imports_granularity = "Crate",wrap_comments— nightly-only after years, a long-standing ecosystem grievance. Teams that want them runcargo +nightly fmtwhile building on stable. - No goimports analog needed: unused imports are compiler warnings and rust-analyzer adds imports on completion, so import management landed in the language server rather than the formatter.
- Skip escape hatch:
#[rustfmt::skip]on an item preserves hand-laid-out tables and macro-heavy code — use sparingly, it rots. - Macro bodies are mostly untouched: rustfmt formats what it can parse as Rust; DSL-ish macro invocations pass through — one reason macro-heavy codebases look less uniform.
Examples
cargo fmt # format the workspace
cargo fmt --check # CI: fail on drift
cargo +nightly fmt # when the team wants the unstable import rules
# rustfmt.toml — the culturally acceptable maximum
max_width = 100
Related
- The Rust toolchain — parent catalog.
- clippy — where style ends and lint begins.
- rust-analyzer — format-on-save and import management in practice.
- gofmt & goimports — the zero-configuration extreme this tool approaches but doesn't reach.