rust-analyzer保存时自动格式化的配置方法

如何在VS Code中配置rust-analyzer,使其在保存文件时自动格式化Rust代码?我已经安装了rust-analyzer扩展,但不知道具体需要设置哪些参数才能实现保存时自动格式化的功能。能否提供详细的配置步骤或示例?

2 回复

settings.json 中添加:

{
  "editor.formatOnSave": true,
  "[rust]": {
    "editor.defaultFormatter": "rust-lang.rust-analyzer"
  }
}

保存时自动格式化 Rust 代码。


在 Rust 项目中配置 rust-analyzer 实现保存时自动格式化,步骤如下:

  1. 安装 rust-analyzer 扩展(VS Code)

    • 在扩展商店搜索 “rust-analyzer” 并安装
  2. 配置设置(任选一种方式):

    • VS Code 设置 UI: 搜索并勾选:

      • Editor: Format On Save
      • Rust-analyzer > Check On Save: Command 设为 "clippy"(可选代码检查)
      • Rust-analyzer > Format On Save 启用
    • settings.json 配置(推荐):

      {
        "editor.formatOnSave": true,
        "rust-analyzer.checkOnSave.command": "clippy",
        "rust-analyzer.formatOnSave.enable": true
      }
      
  3. 确保系统环境正常

    • 安装 Rust 工具链(含 rustfmt):
      rustup component add rustfmt
      
  4. 项目级配置(可选): 在项目根目录创建 rustfmt.toml 自定义格式化规则,例如:

    max_width = 100
    tab_spaces = 4
    

完成配置后,保存 Rust 文件时会自动触发格式化。若遇到问题,可查看 VS Code 的 “Rust Analyzer” 输出面板排查错误。

回到顶部