FAQ - Help and questions

How do I format Rust code automatically with rustfmt and cargo fmt?

#rustfmt#cargo#toolingpublished 0 replies1 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

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.

Checked with rustc 1.93.0 and rustfmt 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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:
src/main.rsrust
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.

  1. After cargo fmt the same file reads:
src/main.rsrust
fn main() {
    let x = 1;
    let y = 2;
    if x < y {
        println!("{}", x + y)
    }
}
exit: 0
  1. 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.

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.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet