Sub topic 2
Formatting code with cargo fmt
What this chapter assumes
This chapter assumes you can write basic Rust, including ownership and borrowing. It also assumes you can create and build a project with Cargo and use a terminal. You don't need to know anything about rustfmt yet.
By the end you will be able to run cargo fmt, check formatting without changing files, understand what the tool does and does not touch, and diagnose the errors people hit most often.
What rustfmt is
rustfmt is the official Rust formatter. It parses your source code into a syntax tree and prints it back out in the community style. The style is documented in the Rust Style Guide. Because the output depends only on the syntax tree and the configuration, two developers who run rustfmt on the same code get the same text.
cargo fmt is a Cargo subcommand that runs rustfmt for you. It finds every Rust file that belongs to the packages in your workspace and formats each one. You rarely need to call the rustfmt binary yourself.
Both tools ship as the rustfmt component of the Rust toolchain. If you installed Rust with rustup using the default profile, you already have it. If cargo fmt reports that the command is missing, install the component:
rustup component add rustfmtA first run
Here is code that compiles but is formatted badly. The indentation is inconsistent, and there are no spaces around operators or after commas.
fn main(){
let numbers=vec![1,2,3];
let total:i32=numbers.iter().sum();
println!("total = {}",total);
}Run the formatter from anywhere inside the package:
cargo fmtrustfmt rewrites the file in place. The result is:
fn main() {
let numbers = vec![1, 2, 3];
let total: i32 = numbers.iter().sum();
println!("total = {}", total);
}rustfmt changed only whitespace and line breaks here. It added a space before the opening brace, indented each statement by four spaces, put spaces around = and after : and ,, and aligned the last println! with its siblings. The program behaves the same as before.
What the formatter changes
rustfmt works on layout. The main rules it applies by default are:
- Four spaces per indentation level, never tabs.
- A maximum line width of 100 characters. Longer expressions are broken across lines.
- Spaces around binary operators and after commas.
- Opening braces on the same line as the item they belong to.
- A trailing comma when a list is spread over several lines.
- Imports within a group of adjacent
uselines sorted alphabetically. - Long method chains split with one call per line.
Some of these behaviours depend on the width of the content. rustfmt tries to fit a construct on one line first. If it doesn't fit in the allowed width, it switches to a vertical layout. You can see this with a function call:
fn main() {
let short = add(1, 2);
let long = add_all_the_things(first_argument_value, second_argument_value, third_argument_value);
println!("{short} {long}");
}
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn add_all_the_things(a: i32, b: i32, c: i32) -> i32 {
a + b + c
}
const first_argument_value: i32 = 1;
const second_argument_value: i32 = 2;
const third_argument_value: i32 = 3;After cargo fmt, the short line stays as it is, but the long line exceeds the width and becomes:
let long = add_all_the_things(
first_argument_value,
second_argument_value,
third_argument_value,
);Note the trailing comma after the last argument. rustfmt adds it in vertical layouts so that adding another argument later produces a one-line diff.
What it does not change
rustfmt does not rename things, remove unused code, or change logic. It will not warn about a variable named first_argument_value that should be uppercase, because naming is a compiler lint and not a formatting concern. Finding that kind of issue is the job of the compiler and of Clippy, which later chapters cover.
rustfmt also leaves comments mostly alone. It re-indents them to match the surrounding code, but by default it does not rewrap the text inside them.
Checking without changing files
In a team workflow you often want to know whether the code is formatted without modifying it. A pre-commit hook or a CI job is the typical case. Use --check:
cargo fmt --all -- --checkThe command line has two parts, separated by --. Arguments before the -- go to cargo fmt. Arguments after it are passed through to rustfmt. So --all is a cargo fmt option, and --check is a rustfmt option.
In check mode, rustfmt prints a diff of every change it would make and leaves the files untouched. The exit status tells scripts what happened:
| Situation | Exit status |
|---|---|
| All files already formatted | 0 |
| At least one file would change | 1 |
| rustfmt could not run, for example a syntax error | Non-zero, with an error message |
The diff output looks like this:
Diff in src/main.rs:1:
-fn main(){
-let numbers=vec![1,2,3];
+fn main() {
+ let numbers = vec![1, 2, 3];Lines starting with - are what the file contains now. Lines starting with + are what rustfmt would write.
Workspaces and `--all`
In a Cargo workspace with several packages, plain cargo fmt formats only the package in your current directory. Add --all to format every member of the workspace:
cargo fmt --allYou can also select one package by name with -p:
cargo fmt -p my_crateUse --all in scripts so the result does not depend on which directory the script starts from.
What files get formatted
cargo fmt starts from the crate roots listed by Cargo, such as src/main.rs and src/lib.rs. It then follows mod declarations to find the other source files. This has some consequences that surprise people:
- A
.rsfile that nomoddeclaration reaches is not formatted. If you comment out amodline, that file silently drops out of formatting. - Files generated into
OUT_DIRby a build script are not formatted, because they are not in your source tree. - Files under
tests/,examples/, andbenches/are formatted, because Cargo lists each of them as a target. - Paths matched by
.gitignoreare not skipped automatically bycargo fmt. They are skipped only if no module or target leads to them.
Formatting a single file or standard input
For quick experiments you can call rustfmt directly on a file:
rustfmt src/main.rsBe aware that rustfmt also formats the modules that the file declares with mod. If you only want to touch one file, that is usually still what you get, but a file with mod declarations pulls its children in.
rustfmt can also read from standard input and write the result to standard output. This is how some editors and scripts use it:
echo 'fn main(){println!("hi");}' | rustfmt --emit stdoutWhen rustfmt is run directly, it defaults to the 2015 edition unless told otherwise. Newer syntax such as async blocks can then fail to parse. Pass --edition 2021 to fix that, or set the edition in a configuration file. cargo fmt avoids this problem because it reads the edition from Cargo.toml.
Common errors and how to read them
Parse errors
rustfmt can only format code it can parse. If a file has a syntax error, rustfmt reports it and skips that file:
error: expected one of `!` or `::`, found `}`
--> src/main.rs:4:1Fix the syntax first. Often cargo check gives a clearer message for the same problem.
Lines that stay too long
Sometimes you run cargo fmt and a line is still wider than the limit. rustfmt does not fail when this happens. It leaves the line as it is, because it has no way to break it. Common causes are long string literals, long single tokens, and deeply nested expressions. rustfmt does not split a string literal across lines. You can fix this yourself by splitting the string, extracting a variable, or using a raw multi-line string.
Code inside macros
rustfmt formats macro invocations that look like function calls, such as println!("{}", x) or vec![1, 2, 3], when the arguments are valid Rust expressions. It does not format the body of macro_rules! definitions in general, and it leaves macro invocations alone when the contents are not parseable as normal Rust. If a block of code in a macro doesn't change when you expect it to, this is the usual reason.
Formatting that fights you
Occasionally the output is not what you would write by hand, for example a table of numbers that you aligned in columns. The next chapters cover configuration and the #[rustfmt::skip] attribute for these cases. For now, accept the default output. The main value of the tool is that nobody has to argue about the details.
Stable and unstable behaviour
rustfmt has many configuration options, but only some are available on the stable toolchain. Options marked unstable need a nightly compiler. If you set one on stable, rustfmt prints a warning and ignores it. This matters because a project can look configured but behave like the default. The configuration chapter covers how to tell the two kinds apart.
The default style itself is also versioned. Changes to the default formatting are held back until a new style edition, so upgrading the toolchain does not suddenly reformat your whole project. Occasionally a new release does still change output for edge cases, such as long chains or comments, so expect a small diff after toolchain upgrades.
A short workflow
A reliable habit looks like this:
- Write or edit code.
- Run
cargo fmt --all. - Run
cargo buildorcargo testto confirm nothing else changed. - Review the diff with
git diffbefore you commit.
Step 3 is a safeguard. rustfmt is designed to keep behaviour identical, and bugs that change it are rare. A build and test run costs little and protects against them.
Summary of commands
| Goal | Command |
|---|---|
| Format the current package | `cargo fmt` |
| Format every workspace member | `cargo fmt --all` |
| Check only, for scripts and CI | `cargo fmt --all -- --check` |
| Format one package by name | `cargo fmt -p my_crate` |
| Format one file directly | `rustfmt --edition 2021 src/main.rs` |
Exercise
You run cargo fmt --all -- --check in a CI job and it exits with status 1 and prints a diff. What does that tell you, and has anything on disk changed?
Show answer
It tells you that at least one file differs from the formatter's output. Nothing on disk has changed, because --check only prints the diff and never writes files. To fix it, run cargo fmt --all locally, review the changes, and commit them.
Exercise
You comment out the line mod utils; in src/main.rs and run cargo fmt. Will src/utils.rs still be formatted? Explain why.
Show answer
No. cargo fmt finds files by following mod declarations from the crate roots, so a file that no mod declaration reaches is skipped without any warning. Restoring the mod utils; line, or formatting the file directly with rustfmt --edition 2021 src/utils.rs, brings it back.
Exercise
In the command cargo fmt --all -- --check, which tool receives --all and which receives --check?
Show answer
--all is received by cargo fmt, which uses it to select every workspace member. --check comes after the -- separator, so it is passed through to rustfmt, which uses it to print a diff instead of writing files.