How to run cargo fmt on save in vscode?

Viewed 7951

Is it possible to make Visual Studio Code run cargo fmt on file save?

4 Answers

Install the extension rust-analyzer (the officially recommended vscode extension), and add the following to settings.json:

"[rust]": {
    "editor.defaultFormatter": "rust-lang.rust-analyzer",
    "editor.formatOnSave": true
}
  1. Install rust-analyzer, if you have not already.
  2. In Visual Studio Code's settings, enable Editor: Format On Save (editor.formatOnSave).

This is what worked for me. In the file settings.json somewhere inside the curly braces insert the following :

    "editor.formatOnSave": true,
    "editor.formatOnType": true,
    "rust-analyzer.rustfmt.enableRangeFormatting": true,
    "[rust]": {
        "editor.defaultFormatter": "matklad.rust-analyzer", 
        "editor.formatOnSave": true 
    },

Current version of the Rust extension > 0.7.8 requires nothing else to be installed. Enable formatOnSave in VS Code settings.json file:

  "[rust]": {
        "editor.formatOnSave": true
    }
Related