Rust Tooling and Code Quality

rustfmt

rustfmt (invoked via cargo fmt) is Rust's official source code formatter. It parses Rust files into an Abstract Syntax Tree (AST) and reprints them according to the official Rust Style Guide, eliminating manual formatting debates across teams and open-source repositories.

Unformatted Source (`src/*.rs`, `tests/*.rs`)
                  |
                  v  `cargo fmt` (or `cargo fmt --check` in CI)
      [ rustfmt AST Formatter ]
      (Applies `style_edition = "2024"` & `rustfmt.toml`)
                  |
                  v
Deterministically Formatted Rust Source Code

Essential cargo fmt Commands

Command Behavior
cargo fmt Formats all .rs files in the current package in place (follows mod declarations from crate roots).
cargo fmt --all Formats all member packages across a Cargo workspace.
cargo fmt --check CI verification mode: exits with code 1 and prints a unified diff if any file is not formatted according to rustfmt.
rustfmt src/custom.rs Formats a standalone .rs file directly (even if not yet attached via mod in src/lib.rs).

Configuring rustfmt.toml and style_edition = "2024"

When edition = "2024" is set in Cargo.toml, rustfmt defaults to style_edition = "2024", which uses version-sorting for use imports (for example, sorting u8 before u16 and u32 before u64, rather than ASCII-lexicographical sorting where u16 came before u8).

You can customize stable formatting options by placing a rustfmt.toml (or .rustfmt.toml) file at the root of your repository:

# File: rustfmt.toml
edition = "2024"
style_edition = "2024"
max_width = 100
tab_spaces = 4
newline_style = "Unix"
use_small_heuristics = "Default"
use_field_init_shorthand = true
use_try_shorthand = true

Skipping Formatting on Specific Items (#[rustfmt::skip])

Sometimes hand-aligned lookup tables, bitmask matrices, or embedded DSLs are clearer when their manual spacing is preserved. Apply the #[rustfmt::skip] attribute to an individual expression, array, struct, or function so rustfmt leaves that item untouched while formatting the rest of the file:

#[rustfmt::skip]
const IDENTITY_3X3: [i32; 9] = [
    1, 0, 0,
    0, 1, 0,
    0, 0, 1,
];

fn trace_3x3(matrix: &[i32; 9]) -> i32 {
    matrix[0] + matrix[4] + matrix[8]
}

fn main() {
    println!("Trace of 3x3 identity matrix: {}", trace_3x3(&IDENTITY_3X3));
}
Trace of 3x3 identity matrix: 3