不灭的焱

革命尚未成功,同志仍须努力 下载Java21

作者:AlbertWen  添加时间:2026-07-13 17:28:38  修改时间:2026-07-19 06:44:49  分类:04.电脑/软件使用  编辑

目录

可以把 VS Code 的 F5 绑定为 Code Runner 的“运行当前文件”。

1. 安装 Code Runner

在 VS Code 扩展中搜索并安装:

Code Runner

扩展作者通常显示为 Jun Han

2. 设置 F5 运行当前文件

按:

Ctrl + Shift + P

搜索并打开:

Preferences: Open Keyboard Shortcuts (JSON)

keybindings.json 中添加:

[
  {
    "key": "f5",
    "command": "code-runner.run",
    "when": "editorTextFocus"
  },
  {
    "key": "shift+f5",
    "command": "code-runner.stop"
  }
]

效果:

  • F5:运行当前打开的文件
  • Shift + F5:停止运行

这会覆盖 VS Code 原来“F5 启动调试”的快捷键。

3. 设置在终端中运行

打开 VS Code 的 settings.json

Ctrl + Shift + P

搜索:

Preferences: Open User Settings (JSON)

添加:

{
  "code-runner.runInTerminal": true,
  "code-runner.saveFileBeforeRun": true,
  "code-runner.preserveFocus": false
}

其中:

"code-runner.runInTerminal": true

表示在 VS Code 内置终端运行,支持程序输入,例如 Rust 的:

std::io::stdin().read_line(&mut input).unwrap();

Rust 项目推荐配置

对于正规的 Cargo 项目,建议让 F5 执行:

cargo run

settings.json 配置:

{
  "code-runner.runInTerminal": true,
  "code-runner.saveFileBeforeRun": true,
  "code-runner.preserveFocus": false,

  "code-runner.executorMap": {
    "rust": "cd $dir && cargo run"
  }
}

不过这里有一个问题:$dir 是当前 .rs 文件所在目录。

例如当前文件是:

my-project/src/main.rs

那么 $dir 是:

my-project/src

Cargo.toml 在:

my-project

因此直接运行可能找不到 Cargo.toml

更推荐打开整个 Rust 项目目录,并使用:

{
  "code-runner.runInTerminal": true,
  "code-runner.saveFileBeforeRun": true,

  "code-runner.executorMap": {
    "rust": "cargo run"
  }
}

完整配置如下:

{
  "code-runner.runInTerminal": true,
  "code-runner.saveFileBeforeRun": true,
  "code-runner.preserveFocus": false,
  "code-runner.clearPreviousOutput": false,

  "code-runner.executorMap": {
    "rust": "cargo run"
  }
}

此时需要确保 VS Code 打开的是项目根目录:

my-project/
├── Cargo.toml
└── src/
    └── main.rs

然后打开 src/main.rs,按 F5,实际执行:

cargo run

运行独立的 Rust 文件

若当前文件不是 Cargo 项目,只是一个单独的文件,例如:

demo.rs

macOS/Linux 可以配置:

{
  "code-runner.runInTerminal": true,
  "code-runner.saveFileBeforeRun": true,

  "code-runner.executorMap": {
    "rust": "cd $dir && rustc --edition 2024 $fileName -o $fileNameWithoutExt && ./$fileNameWithoutExt"
  }
}

F5 时,相当于执行:

rustc --edition 2024 demo.rs -o demo
./demo

Windows PowerShell 可以配置为:

{
  "code-runner.runInTerminal": true,
  "code-runner.saveFileBeforeRun": true,

  "code-runner.executorMap": {
    "rust": "cd $dir; rustc --edition 2024 $fileName -o $fileNameWithoutExt.exe; .\\$fileNameWithoutExt.exe"
  }
}

最终推荐

你现在开发 Rust Cargo 项目,建议使用:

keybindings.json

[
  {
    "key": "f5",
    "command": "code-runner.run",
    "when": "editorTextFocus"
  },
  {
    "key": "shift+f5",
    "command": "code-runner.stop"
  }
]

settings.json

{
  "code-runner.runInTerminal": true,
  "code-runner.saveFileBeforeRun": true,
  "code-runner.preserveFocus": true,

  "code-runner.executorMap": {
    "rust": "cargo run"
  }
}

使用时用 VS Code 打开包含 Cargo.toml 的项目根目录,而不是单独打开 main.rs 文件。