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#
- Format everything:
cargo fmt. - In CI, check without changing anything. This unformatted file shows what
--checkprints:
fn main(){
let x=1;let y = 2;
if x<y {println!("{}",x+y)}
}> 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: 1The exit code is 1 when anything would change and 0 when everything is formatted.
- After
cargo fmtthe same file reads:
fn main() {
let x = 1;
let y = 2;
if x < y {
println!("{}", x + y)
}
}
exit: 0- To change the style, put a
rustfmt.tomlnext toCargo.toml, for examplemax_width = 100. Most projects keep the defaults.
Common mistakes#
- Formatting only some files and committing the rest unformatted. A later
cargo fmtthen touches lines that have nothing to do with your change. Format as you go. - Expecting
cargo fmtto 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.