Rust Reference ยท Tools
cargo fmt
Reference for cargo fmt: format a whole package with rustfmt, check formatting in CI, skip items with #[rustfmt::skip] and understand what it changes.
cargo fmt runs rustfmt over every source file of your package (or workspace) and rewrites them in the standard Rust style. It only changes layout: whitespace, line breaks, trailing commas, import order within a group. The meaning of the program never changes, and formatting is idempotent, so running it twice gives the same result.
The tool ships with rustup as the rustfmt component. Settings live in rustfmt.toml (see rustfmt.toml). This page is a read-only command reference; the examples show code before and after formatting.
$ cargo fmt
$ cargo fmt --check
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
cargo fmt [options] [-- <rustfmt options>]
| Name | Description |
|---|---|
--check |
Change nothing; print a diff and exit with code 1 if any file would change. Use it in CI. |
--all |
Format every workspace member (default is the current package). |
-p, --package |
Format only the named package. |
-- --edition 2024 |
Arguments after -- go straight to rustfmt. |
--manifest-path |
Format the package whose Cargo.toml you point at. |
--message-format |
human (default) or short. |
Exit codes: 0 when everything is formatted (or was formatted), 1 for --check differences, other non-zero for errors such as code that does not parse.
Usage notes
cargo fmtfollowsmoddeclarations, so it finds files insrc/automatically, including generated-by-hand modules.- Code that does not parse is skipped with an error; fix the syntax first.
- Apply
#[rustfmt::skip]to an item, statement or expression when manual layout carries meaning.#![rustfmt::skip]at a file top skips the whole file. - Macro bodies are formatted only when they look like valid Rust (for example
vec![...]orprintln!(...)). Macros with custom syntax are left alone. - Run
cargo fmt --checkas a CI step so style never appears in review comments. See Clippy, rustfmt and code quality. - Editors usually call
rustfmtdirectly on save; it reads the same configuration files. - Teams should pin one
rustfmt.toml; stable options only keep things portable.
Related
- rustfmt.toml, cargo clippy, rustup
- Tutorial: Clippy and rustfmt