# How do I format Rust code automatically with rustfmt and cargo fmt?
Source: https://ruststudio.org/community/t/120/how-do-i-format-rust-code-automatically-with-rustfmt-and-cargo-fmt
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0 and rustfmt 1.93.0, Windows 11
Category: Help and questions | Kind: FAQ | Tags: rustfmt, cargo, tooling | Views: 1

## Short answer
rustfmt is Rust's standard formatter. Run cargo fmt to rewrite every file in the project to the standard style, or cargo fmt --check to only report differences and exit with a failure code, which is what CI should use. Settings go in a rustfmt.toml file.

## Answer
## Answer
The Rust community uses one default style, applied by `rustfmt`, so code looks the same in every project and style is never argued in reviews. `cargo fmt` formats all the files of the crate (or of every workspace member).

## How to do it
1. Format everything: `cargo fmt`.
2. In CI, check without changing anything. This unformatted file shows what `--check` prints:

```rust title=src/main.rs (before)
fn main(){
    let x=1;let y = 2;
    if x<y {println!("{}",x+y)}
}
```

```text
> cargo fmt --check
Diff in C:\dev\project\src\main.rs:1:
-fn main(){
-    let x=1;let y = 2;
-    if x<y {println!("{}",x+y)}
+fn main() {
+    let x = 1;
+    let y = 2;
+    if x < y {
+        println!("{}", x + y)
+    }
 }
 
exit: 1
```

The exit code is 1 when anything would change and 0 when everything is formatted.
3. After `cargo fmt` the same file reads:

```rust title=src/main.rs (after)
fn main() {
    let x = 1;
    let y = 2;
    if x < y {
        println!("{}", x + y)
    }
}
exit: 0
```

4. To change the style, put a `rustfmt.toml` next to `Cargo.toml`, for example `max_width = 100`. Most projects keep the defaults.

## Common mistakes
- Formatting only some files and committing the rest unformatted. A later `cargo fmt` then touches lines that have nothing to do with your change. Format as you go.
- Expecting `cargo fmt` to change names or logic. It only changes whitespace and layout.

## Related questions
### Can I format on save?
Editors that talk to rust-analyzer can format the open file; the command line version is `cargo fmt`.

## In Ruststudio
Run > Format Project (cargo fmt) formats the whole project. Edit > Format Document (Shift+Alt+F) formats the open saved Rust file through rust-analyzer; when rust-analyzer is not running Ruststudio says so and points to Format Project.
