Sub topic 2
Formatting code with cargo fmt
This chapter assumes you can write basic Rust, create and build a project with Cargo, and use a terminal. It covers how to run rustfmt through Cargo, how to check formatting without changing files, and what the tool does and does not touch.
What rustfmt does
rustfmt is the official Rust formatter. It parses your source into a syntax tree and prints it back in the standard Rust style. The default style uses four-space indentation, a maximum line width of 100 characters, and consistent spacing around operators, braces, and commas.
Because rustfmt works from the parsed code and not from the text, the result does not depend on how you typed the original. Two programs with the same syntax tree produce the same output. Style arguments in code review go away, and diffs show only real changes.
rustfmt ships as a rustup component. If cargo fmt reports that the command is missing, install it:
rustup component add rustfmtRunning cargo fmt
You usually call rustfmt through Cargo. cargo fmt finds every source file in the current package and formats it in place. Here is code with inconsistent indentation and spacing:
fn main(){
let numbers=vec![1,2,3];
let total:i32=numbers.iter().sum();
println!("total = {}",total);
}After you run cargo fmt, the file becomes:
fn main() {
let numbers = vec![1, 2, 3];
let total: i32 = numbers.iter().sum();
println!("total = {}", total);
}The behavior is the same. Only whitespace and line breaks changed.
Checking without changing files
Sometimes you want to know whether files are formatted, without rewriting them. This is the case in CI and in pre-commit hooks. Pass --check to rustfmt through Cargo:
cargo fmt
cargo fmt --all -- --checkThe first command rewrites files. The second prints a diff for each file that differs and exits with a non-zero status if any file is not formatted. It leaves the files unchanged.
The two parts of the second command do different jobs:
--allformats every package in a Cargo workspace. Without it,cargo fmthandles only the package in the current directory.- Arguments after the bare
--go torustfmtitself, not to Cargo.--checkis one of them.
What gets formatted
cargo fmt starts from each target's root file, such as src/main.rs or src/lib.rs. It follows mod declarations to find the other files. A .rs file that no mod declaration reaches is not formatted. If a file seems to be ignored, check that it is declared as a module.
rustfmt also needs code that parses. If a file has a syntax error, rustfmt reports the error and skips that file. Fix the syntax first.
It also leaves some things alone:
- It keeps comments, but it does not rewrap their text by default.
- It cannot break a line that has no legal break point, such as a very long string literal. That line stays over the limit and no error is shown.
- Where an item has no safe way to be reformatted, it leaves the item as written.
A quick workflow
- Write or edit code without worrying about layout.
- Run
cargo fmtto normalize it. - Run
cargo fmt --all -- --checkto confirm the whole workspace is clean. A non-zero exit means something is still unformatted. - Commit.
The next chapters show how to adjust the style with a rustfmt.toml file and how to exclude individual items from formatting.
Exercise
You run cargo fmt --all -- --check in CI and it exits with a non-zero status. What did the command change in your files, and what should you do to fix the build?
Show answer
It changed nothing. --check only prints a diff and reports failure when files differ from the standard style. To fix the build, run cargo fmt locally to rewrite the files, review the changes, commit them, and push again.
Exercise
You add a new file src/helpers.rs with messy indentation, run cargo fmt, and the file is unchanged. What is the most likely cause?
Show answer
No mod helpers; declaration reaches the file from src/main.rs or src/lib.rs. cargo fmt follows mod declarations from the crate root, so an undeclared file is not formatted. Adding mod helpers; fixes this. A syntax error in the file would also make rustfmt skip it, but it would print an error.