Introduction
rustfmt is the official code formatter for Rust, maintained by the Rust project. It automatically reformats Rust source code to conform to the official Rust style guide, eliminating style debates and ensuring consistency across teams and open-source projects.
What rustfmt Does
- Formats Rust source files to follow the official Rust style guide
- Integrates with
cargo fmtfor project-wide formatting in a single command - Supports a
--checkmode that returns a non-zero exit code on unformatted code for CI gating - Handles complex Rust syntax including macros, attributes, and where clauses
- Reads configuration from a
rustfmt.tomlfile for project-level customization
Architecture Overview
rustfmt parses Rust source code using the compiler's own parser (via rustc internals) to produce an AST. It then walks the AST and emits reformatted source text, preserving comments and attributes. The formatter handles whitespace, line breaking, and indentation according to configurable rules. It is distributed as a rustup component and invoked through the cargo toolchain.
Self-Hosting & Configuration
- Installed automatically with most Rust toolchains; add manually with
rustup component add rustfmt - Configure via
rustfmt.tomlor.rustfmt.tomlin the project root - Key options include
max_width(default 100),tab_spaces,edition(2015/2018/2021), anduse_small_heuristics - Run on save in editors via rust-analyzer integration
- Use
--edition 2021flag to match your project's Rust edition
Key Features
- Zero-config defaults that match the official Rust style guide
- Stable and nightly channels with different sets of configurable options
- Preserves meaningful blank lines and respects
#[rustfmt::skip]attributes - Formats code inside doc comments when using nightly
- Deterministic output ensures the same code always produces the same formatting
Comparison with Similar Tools
- Prettier — JavaScript/TypeScript formatter; rustfmt fills the same role for Rust
- Black — Python formatter with a similar zero-config philosophy
- gofmt — Go's built-in formatter; rustfmt was inspired by gofmt's approach
- clang-format — C/C++ formatter; more configurable but requires more setup than rustfmt
FAQ
Q: Can I override the default style?
A: Yes. Place a rustfmt.toml in your project root. Some options are stable; others require the nightly toolchain.
Q: How do I skip formatting for a block of code?
A: Add #[rustfmt::skip] before the item, or use // rustfmt::skip for expressions.
Q: Does rustfmt work with macros? A: rustfmt formats most macro invocations. Complex procedural macros may be left unformatted.
Q: Should I run rustfmt in CI?
A: Yes. Use cargo fmt -- --check in CI to enforce consistent formatting across all contributions.