Sub topic 3
Configuring rustfmt
This chapter assumes you can already run cargo fmt and read its effect on a file. It covers how to change rustfmt's defaults with a configuration file, which options are safe to use, and what goes wrong most often.
Why configure at all
The defaults come from the Rust style guide, and most projects should keep them. Configuration is for a few project-level choices, such as a wider line limit. Every option you change makes your code look different from most other Rust code. Contributors then have to learn your deviations, so change only what you can justify.
The configuration file
rustfmt reads a TOML file named rustfmt.toml or .rustfmt.toml. For each source file, it looks in that file's directory and then in each parent directory. It uses the first config file it finds. Put the file at the root of your workspace and it applies to every crate below it.
# rustfmt.toml
max_width = 100
edition = "2021"
use_field_init_shorthand = trueEach line sets one option:
max_widthis the maximum line length. The default is 100, so a value of 100 changes nothing. Use it to raise or lower the limit.editiontells rustfmt which Rust edition's syntax to parse. When you runcargo fmt, Cargo passes the package's edition to rustfmt. The setting matters most when you runrustfmtdirectly on a file.use_field_init_shorthandrewritesPoint { x: x }asPoint { x }.
Here is code that the last option changes:
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let x = 1;
let y = 2;
let p = Point { x: x, y: y };
println!("{:?}", p);
}After cargo fmt with that configuration, the line becomes let p = Point { x, y };. Without the option, rustfmt leaves it alone.
Checking which settings are in effect
You can ask rustfmt to print the configuration it resolved for a file:
rustfmt --print-config current src/main.rsThis prints every option with its current value. It is the quickest way to confirm that your file was found and parsed. If your change has no effect, run this first.
How rustfmt finds a config
Only one file is used. rustfmt does not merge a config in a subdirectory with one at the root, so a nested file must repeat every option you still want.
Stable and unstable options
Some options work only on nightly Rust. Examples are imports_granularity, group_imports, wrap_comments, and format_code_in_doc_comments. On a stable toolchain, rustfmt prints a warning that the option is unstable and ignores it. The rest of the file still applies.
This produces a quiet failure. A teammate on nightly sees one result, and CI on stable sees another. If your CI uses stable, as the CI chapter later in this tutorial does, keep the config to stable options. The ones you will use most are in this table:
| Option | Default | Effect |
|---|---|---|
| `max_width` | `100` | Maximum line length |
| `tab_spaces` | `4` | Spaces per indent level |
| `newline_style` | `"Auto"` | Line endings: `"Unix"`, `"Windows"`, or detected |
| `use_small_heuristics` | `"Default"` | How eagerly short items are kept on one line |
| `use_field_init_shorthand` | `false` | Rewrites `x: x` as `x` |
| `use_try_shorthand` | `false` | Rewrites `try!(...)` as `...?` |
Common errors
- Config ignored. The file is misnamed (
rustfmt.tml) or sits in a directory that is not a parent of the source file. Use--print-config currentto check. - Parse error. TOML requires quotes around strings.
edition = 2021is wrong, andedition = "2021"is right. - Unknown option. A typo in an option name produces a warning, and rustfmt then uses the default. Read the warnings.
- Formatting differs between machines. Different rustfmt versions format some code differently. Pin the toolchain with a
rust-toolchain.tomlfile if your team sees churn.
Exercise
Your team's CI runs on stable Rust. A teammate adds group_imports = "StdExternalCrate" to rustfmt.toml, and locally on nightly the imports are reordered. After the change, cargo fmt --all -- --check still passes in CI even though imports are not grouped. Why, and how would you confirm it?
Show answer
group_imports is an unstable option. The stable rustfmt prints a warning and ignores it, so CI checks formatting without grouping. To confirm, run rustfmt --print-config current src/main.rs or cargo fmt on the stable toolchain and read the warning. The fix is to remove the option or run formatting on nightly everywhere.