Sub topic 3
Configuring rustfmt
This chapter assumes you can run cargo fmt on a project, as covered in the previous chapter, and that you can read a small TOML file. Here you will learn where rustfmt looks for configuration, which options are worth changing, and the errors people usually hit when they do.
Why configure at all
The default rustfmt style is the community standard. Most projects never change it, and that is a good outcome: any Rust developer can read the code without adjusting to local taste.
Configuration still has legitimate uses:
- A team prefers a wider line limit than the default of 100 columns, or a narrower one.
- A project must declare the Rust edition so rustfmt parses code the same way the compiler does.
- A small number of style choices, such as field init shorthand, are enforced across the codebase.
Keep the file short. Every option you set is a difference from the style readers expect, and a difference is a cost.
Where rustfmt finds its configuration
rustfmt looks for a file named rustfmt.toml or .rustfmt.toml. Both names mean the same thing. It starts in the directory of the file being formatted and walks up through parent directories until it finds one. If it reaches the filesystem root without finding a file, it falls back to your user configuration directory, and then to the built-in defaults.
Two consequences follow from this search:
- In a Cargo workspace, put one
rustfmt.tomlat the workspace root. Every member crate finds it by walking upward, so the whole workspace shares one style. - A
rustfmt.tomlin a member crate overrides the root file for that crate. rustfmt uses the first file it finds and does not merge it with files higher up. If you add a crate-level file, repeat any root options you still want.
You can see which file rustfmt actually used with the --print-config flag. Running rustfmt --print-config current src/main.rs prints the effective configuration for that file. The --print-config default form prints the defaults, which is a convenient way to list every option.
A starter configuration
This file uses only options available on the stable toolchain:
# rustfmt.toml
max_width = 100
edition = "2021"
use_field_init_shorthand = trueWhat each line does:
max_widthsets the maximum line length in columns. rustfmt wraps code to stay under it. The default is 100, so the value here matches the default. Change it to120if your team wants longer lines.editiontells rustfmt which Rust edition to parse. When you runcargo fmt, Cargo passes the edition fromCargo.tomlautomatically. The setting matters when you runrustfmtdirectly on a file, where there is no manifest to read.use_field_init_shorthandrewritesPoint { x: x, y: y }asPoint { x, y }.
Here is the effect of the last option. Given this input:
struct Point {
x: i32,
y: i32,
}
fn make(x: i32, y: i32) -> Point {
Point { x: x, y: y }
}
fn main() {
let p = make(1, 2);
println!("{} {}", p.x, p.y);
}cargo fmt with use_field_init_shorthand = true changes the body of make to Point { x, y }. Without the option, rustfmt leaves x: x alone, because it treats that as a choice about code rather than layout. Clippy also has a lint about redundant field names, so the two tools agree on this style.
Stable and unstable options
rustfmt has many options, but only some are available on the stable toolchain. The rest are unstable. They are marked in the documentation and in --print-config default output, and they work only on a nightly toolchain.
If you set an unstable option while using stable Rust, rustfmt does not stop. It prints a warning such as Warning: can't set 'imports_granularity = Crate', unstable features are only available in nightly channel, ignores that line, and formats with the rest of your file. The failure is quiet in a CI log, and it means a teammate on nightly sees different output from everyone else.
If you do need an unstable option, you can run nightly rustfmt only for formatting while building with stable:
cargo +nightly fmtDecide this once for the project and put the same command in CI. Mixing the two is where most "my formatter disagrees with CI" reports come from.
Options worth knowing
The table lists commonly used stable options. Check the current list with rustfmt --print-config default before relying on it, because options move from unstable to stable over time.
| Option | Default | Effect |
|---|---|---|
| `max_width` | `100` | Maximum line length |
| `hard_tabs` | `false` | Use tabs instead of spaces for indentation |
| `tab_spaces` | `4` | Spaces per indentation level |
| `newline_style` | `"Auto"` | Line endings: `"Auto"`, `"Unix"`, `"Windows"`, or `"Native"` |
| `use_small_heuristics` | `"Default"` | How aggressively short expressions stay on one line |
| `use_field_init_shorthand` | `false` | Rewrite `x: x` as `x` in struct literals |
| `use_try_shorthand` | `false` | Rewrite `try!(expr)` as `expr?` |
| `reorder_imports` | `true` | Sort `use` declarations alphabetically |
| `edition` | `"2015"` | Edition used to parse the code |
Two options deserve a closer look.
newline_style matters on teams that mix Windows and Linux. With "Auto", rustfmt keeps whatever line ending the file already uses. If one developer's editor converts a file to CRLF, the diff shows every line as changed. Setting newline_style = "Unix" makes rustfmt normalize the endings so that the diff stays small.
use_small_heuristics controls when rustfmt keeps a short struct literal or function call on a single line. The value "Max" keeps more code on one line, "Off" splits more, and "Default" sits between them. Changing it alters the layout of a lot of code at once, so treat it like a global style decision.
Setting options from the command line
You can pass options to the rustfmt binary without a file, using --config:
rustfmt --config max_width=80,use_field_init_shorthand=true src/main.rsThrough Cargo, put the options after --:
cargo fmt -- --config max_width=80Command-line values override the file. This is useful for an experiment: try a new max_width and look at the diff with git diff before you commit to writing it into rustfmt.toml. For anything the team should share, use the file, because a command-line option exists only in the history of your shell.
Checking that your configuration is applied
A configuration file that rustfmt silently ignores is a common problem. Use this short routine whenever you add or change an option.
- Create a file with a deliberately long line.
- Run
cargo fmt --all -- --check. The--checkflag reports differences and exits with a non-zero status, without changing files. - Lower
max_widthto a small value such as40and run the check again. The report should now list more differences. - Restore the real value.
If the report does not change, rustfmt is not reading your file. The usual causes are below.
| Symptom | Likely cause | Fix |
|---|---|---|
| No change after editing the file | File is misnamed, for example `rustfmt.tml` or `rustfmt.toml.txt` | Rename to `rustfmt.toml` or `.rustfmt.toml` |
| Option ignored with a warning about nightly | Unstable option on the stable toolchain | Remove it or use `cargo +nightly fmt` everywhere |
| One crate ignores the workspace style | A `rustfmt.toml` in that crate shadows the root file | Delete the crate-level file or copy the options into it |
| Parse error in the TOML | Wrong value type, such as `max_width = "100"` | Use a number: `max_width = 100` |
| Different output on CI and locally | Different toolchain versions | Pin the toolchain, for example with a `rust-toolchain.toml` file |
On that last row: rustfmt output can change slightly between releases, even for stable options. Pinning the toolchain version keeps local and CI results identical.
Option names and typos
rustfmt does not accept unknown keys quietly in every case. A misspelled option usually produces an error that names the bad key, and the run stops before any file is formatted. This is the safer failure, so read the first line of output when cargo fmt suddenly refuses to run after a config change.
TOML itself is strict about types. Numbers are bare, strings are quoted, and booleans are lowercase true or false. Enumerated options take quoted strings with the exact capitalization shown in the documentation, so newline_style = "unix" is wrong and newline_style = "Unix" is correct.
Exercises
Exercise
Your workspace has a rustfmt.toml at the root that sets max_width = 120. You add a rustfmt.toml inside one member crate that contains only use_field_init_shorthand = true. What line width does that crate use, and why?
Show answer
It uses the default of 100. rustfmt uses the first configuration file it finds while walking up from the source file, and it does not merge files. The crate-level file wins completely, so max_width = 120 from the root is not applied. To keep both settings, add max_width = 120 to the crate-level file or delete that file.
Exercise
A teammate adds imports_granularity = "Crate" to rustfmt.toml. CI uses stable Rust and passes, but the teammate's nightly toolchain reformats imports on save. Explain the mismatch and give two ways to resolve it.
Show answer
imports_granularity is an unstable option. Stable rustfmt prints a warning and ignores it, so CI formats without it. Nightly rustfmt applies it, so the teammate's editor produces different output. Resolve it by either removing the option so everyone uses stable defaults, or by using nightly rustfmt everywhere, for example cargo +nightly fmt locally and in CI, with the nightly version pinned.
Exercise
Write the command that verifies formatting for the whole workspace without modifying any file, and state what it returns when a file needs changes.
Show answer
cargo fmt --all -- --check. It prints the differences it would make and exits with a non-zero status. When every file is already formatted it exits with status 0.