🎓 A1Learner
🔍

Rust Formatting with rustfmt

rustfmt is a program that rewrites code into the one shared Rust style. cargo runs rustfmt for a whole project.

Cramped code

This program works. It is squeezed onto two lines, and it is hard to read:

fn add(a:i32,b:i32)->i32{a+b}
fn main(){let total=add(20,22);println!("total = {total}");}

One command later

cargo fmt rewrites the file into the standard shape. Spaces land where they belong. Each statement gets its own line:

fn add(a: i32, b: i32) -> i32 {
    a + b
}
fn main() {
    let total = add(20, 22);
    println!("total = {total}");
}

Check without touching

A pipeline wants a verdict, not a rewrite. The check form prints a diff and fails the step. A clean project passes the same check with exit code 0:

// in your terminal:
// $ cargo fmt --check

One setting of your own

A long line fits the default 100 columns. Put max_width = 40 in rustfmt.toml and the same run wraps it:

fn main() {
    let message = format!("{} {} {} {}", "one", "two", "three", "four");
    println!("{message}");
}

Hands off one item

Some code is aligned on purpose, like a small table. The skip attribute protects that one item. The rest of the file still gets formatted:

#[rustfmt::skip]
fn untouched() -> (i32, i32) {
    let a    = 1;
    let b = 2;
    (a, b)
}

Example

#[rustfmt::skip]
fn untouched() -> (i32, i32) {
    let a    = 1;
    let b = 2;
    (a, b)
}

fn main() {
    let pair = untouched();
    println!("pair = {:?}", pair);
}

Key points

  • Use cargo fmt to format every file in a project in one go.
  • Use rustfmt on its own to format a single file
  • Use cargo fmt --check in scripts and in CI.
  • It changes nothing.
  • It prints the differences.
  • It fails with exit code 1 when any file is off-style
  • Your few choices live in a file named rustfmt.toml at the project root.
  • A line like max_width = 40 is read on every run
  • Use #[rustfmt::skip] above one item to keep hand-aligned code exactly as you wrote it
  • rustfmt moves layout only.
  • It never renames anything.
  • It never reorders anything.
  • It never changes what the code does
  • One shared look means no team ever argues about brace placement again.
  • rustfmt gives every file it touches the same layout.

In this example, the file has been through cargo fmt once. The skip attribute guarded the untouched function, so its wide spacing survives. main wears the standard shape, with one statement per line. The program builds the pair (1, 2) and prints pair = (1, 2). Format a file twice and the second run changes nothing. The style is a fixed point.

Note

The Rust style is barely configurable on purpose.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

CI runs cargo fmt --check and the step fails. The code itself compiles fine. What happened?