How to Use cargo fmt to Format Rust Code

Run `cargo fmt` in your project root to automatically format all Rust source files according to the official style guide.

Run cargo fmt in your project root to automatically format all Rust source files according to the official style guide. By default, it modifies files in place, but you can use the --check flag to verify formatting without making changes, which is ideal for CI pipelines.

Here is the basic command to format your entire workspace:

cargo fmt

If you need to check formatting without altering files (e.g., to fail a build if code is unformatted), use the --check flag:

cargo fmt --check

You can also target specific files or directories. For example, to format only a single file or a specific subdirectory:

cargo fmt src/main.rs
cargo fmt -- src/utils/

Note the double dash -- before the path; it separates cargo fmt options from the file paths.

For projects using rustfmt.toml, cargo fmt automatically picks up your custom configuration. If you don't have a config file, it uses the default rustfmt settings. To see what rustfmt would change without applying it, combine --check with --verbose:

cargo fmt --check --verbose

This outputs the diff of changes, helping you understand exactly what the formatter will do.

If you are using an IDE like VS Code or RustRover, ensure the "Format On Save" feature is enabled. These editors typically invoke cargo fmt or rustfmt directly behind the scenes. If you encounter issues where the IDE uses a different version of rustfmt than your CLI, you can force the toolchain to match by running:

rustup component add rustfmt

This ensures your local environment has the latest formatter component installed. Remember that cargo fmt only handles formatting; it does not fix logic errors or enforce linting rules. For linting, you should pair it with cargo clippy.

In a CI environment, you typically add a step that runs cargo fmt --check to ensure no unformatted code is merged. If the command exits with a non-zero status, the build fails, preventing style inconsistencies from entering the codebase.