You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置VS Code使Rust文件保存时使用nightly版rustfmt并应用style_edition配置

如何配置VS Code使Rust文件保存时使用nightly版rustfmt并应用style_edition配置

我来帮你搞定这个问题!要让VS Code在保存Rust文件时自动调用nightly版的rustfmt,同时读取你rustfmt.toml里的style_edition = "2024"配置,只需要调整VS Code的设置就行,步骤很简单:

1. 先确认安装nightly Rust工具链

如果还没装nightly版本,先打开终端跑这个命令:

rustup install nightly

2. 修改你的.vscode/settings.json

打开你已经有的那个.vscode/settings.json文件,在现有配置的基础上,添加rust-analyzer的rustfmt相关配置。最终的配置大概是这样:

{
  "[rust]": {
    "editor.inlayHints.enabled": "offUnlessPressed",
    "editor.defaultFormatter": "rust-lang.rust-analyzer",
    "editor.formatOnSave": true
  },
  "rust-analyzer.rustfmt.command": "cargo",
  "rust-analyzer.rustfmt.extraArgs": [
    "+nightly",
    "fmt",
    "--"
  ]
}

3. 让配置生效

保存settings.json之后,记得重启VS Code,或者按下Ctrl+Shift+P(Windows/Linux)/Cmd+Shift+P(Mac),选择"Reload Window"选项,让新配置加载生效。

补充:另一种直接调用rustfmt的配置方式

如果你不想通过cargo中转,也可以直接指定nightly版的rustfmt二进制文件,把配置改成这样:

"rust-analyzer.rustfmt.command": "rustfmt",
"rust-analyzer.rustfmt.extraArgs": [
  "+nightly"
]

不过用cargo的方式更稳妥,它会自动适配你项目的rustup环境配置。

最后你可以验证一下:故意写一段不符合nightly格式化规则的Rust代码,保存后看是否按照rustfmt.toml的要求格式化,或者和cargo +nightly fmt的结果对比,确保一致就行。

备注:内容来源于stack exchange,提问作者muturgan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 09:53:10