环境:在WSL(ubuntu20.04)中使用vscode
(1)在WSL 中安装rust,cargo
wangji@script-wang:~/code/rust/greeting/src$ sudo apt install rustc -y
wangji@script-wang:~/code/rust/greeting/src$ sudo apt install rustfmt -y
wangji@script-wang:~/code/rust/greeting/src$ sudo apt-get -y install cargo
(2)在vscode中安装rust-analyzer
(3)配置vscode编译:打开vscode,终端->运行任务->配置任务->使用模板生成task.json文件->others,会在工程目录的.vscode中生成tasks.json
参考配置如下:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "wangji rust build debug",
"type": "shell",
"command": "cargo",
"args": [
"build"
]
},
{
"label": "wangji rust build release",
"type": "shell",
"command": "cargo",
"args": [
"build --release"
]
}
]
}
编译:终端->运行任务->wangji rust build->
(4)配置vscode调试:点击vscode这里
也会在工程目录下的.vscode中生成一个launch.json文件
可用的配置如下:
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Debug",
"type": "gdb",
"request": "launch",
"target": "${workspaceFolder}/target/debug/${workspaceFolderBasename}",
"cwd": "${workspaceRoot}",
"valuesFormatting": "parseText"
},
{
"name": "Release",
"type": "gdb",
"request": "launch",
"target": "${workspaceFolder}/target/release/${workspaceFolderBasename}",
"cwd": "${workspaceRoot}",
"valuesFormatting": "parseText"
}
]
}
[Error - 10:02:32 AM] Request textDocument/formatting failed.
Message: Failed to spawn cd "/home/wangji/code/rust/greeting/src" && "rustfmt" "--edition" "2021"
Code: -32603
观察vscode输出发现没有安装rustfmt命令,安装即可:
wangji@script-wang:~/code/rust/greeting/src$ sudo apt install rustfmt -y
cargo clippy: 类似eslint,lint工具检查代码可以优化的地方
cargo fmt: 类似go fmt,代码格式化
cargo tree: 查看第三方库的版本和依赖关系
cargo bench: 运行benchmark(基准测试,性能测试)
cargo udeps(第三方): 检查项目中未使用的依赖
另外 cargo build/run --release 使用 release 编译会比默认的 debug 编译性能提升 10 倍以上,但是 release 缺点是编译速度较慢,而且不会显示 panic backtrace 的具体行号
具体用法见:Debugging Rust apps with GDB
打开或新建用户目录下/.cargo/config文件
在文件中增加配置
[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"
replace-with = 'tuna'
[source.tuna]
registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"
ref: