Rust初入门 -- 03 使用vscode对rust开发调试

vscode rust

使用vscode对rust开发调试
首先安装rust插件
Rust
Rust Extension Pack
Rust Test Explorer

配置开发

以Mac为例,cmd + shirft + p打开命令面板,输入:

1
tasks

选择 Tasks: Configure Default Build Task,再选择:Rust: cargo build
task
cargo-build

vscode就会生成:.vscode/tasks.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"type": "cargo",
"subcommand": "build",
"problemMatcher": [
"$rustc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

将”subcommand”: “build” 改成 :”subcommand”: “run”
这样按cmd + shirft + B,就能直接运行:

1
2
3
4
5
6
7
> Executing task: cargo run <

Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/vscode-rust`
Hello, world!

Terminal will be reused by tasks, press any key to close it.

配置测试task

在src/main.rs添加测试方法:

1
2
3
4
#[test]
fn fail() {
unimplemented!();
}

以Mac为例,cmd + shirft + p打开命令面板,输入:

1
tasks

选择 Tasks: Configure Default Test Task,再选择:Rust: cargo test
cargo test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
> Executing task: cargo test <

Compiling vscode-rust v0.1.0 (/Users/zhaoxiongliang/work/github/jsl6/rust-learn/03-vscode-rust)
Finished test [unoptimized + debuginfo] target(s) in 0.44s
Running target/debug/deps/vscode_rust-e3d6a94d5c6c8ae6

running 1 test
test fail ... FAILED

failures:

---- fail stdout ----
thread 'fail' panicked at 'not yet implemented', src/main.rs:6:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.


failures:
fail

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out

error: test failed, to rerun pass '--bin vscode-rust'
The terminal process terminated with exit code: 101

Terminal will be reused by tasks, press any key to close it.

Debug环境

安装:
C/C++ extension.
Native Debug

!在Debug菜单,Add Congfigration,选择“C++ (Windows)” environment”
debug
生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(lldb) 启动",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/a.out",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "lldb"
}
]
}

将”program”: “${workspaceFolder}/a.out”,改成:

1
"program": "${workspaceFolder}/target/debug/vscode-rust",

在main.rs打上断点,在debug模式下启动,就能进入程序调试:
rust debugger