一、简介

本文介绍了如何使用vscode编写rust,实现打印"Hello, world!"的程序。

二、工具安装

0. 环境介绍

Linux (或者windows+wsl)

1. 安装rust编译器rustc和包管理器cargo

请参考连接:Rust 程序设计语言 简体中文版-安装。 rust编译器安装完成后,会自动安装cargo。cargo是Rust的包管理器,可以用来方便的进行包管理、编译运行rust程序。 可以使用以下命令查看是否成功安装rust编译器和cargo。

rustc -V

cargo -V

2. vscode插件安装

安装rust-analyzer和CodeLLDB(用于debug)。

三、实现helloworld

接下来将使用cargo进行管理我们的程序(尽管程序只打印“Hello, world!”一句话)。

1. 新建hello_world工程

cargo new hello_world

此时目录下自动生成一个名字为hello_world/的文件夹。

2. 使用vscode打开工程目录文件夹

使用vscode打开hello_world/文件夹,文件结构如下。

3. 编写main.rs文件

编辑main.rs文件,main.rs文件如下:

fn main() {

println!("Hello, world!");

}

4. 编译程序

编译我们的hello_world工程。在hello_world/目录下运行以下命令。

cargo build

输出结果如下所示: 编译器的输出表示程序hello_world已经编译成功,耗时0.30s。

5. 运行程序

使用以下命令运行程序。

cargo run

若运行成功,运行结果如下: 可以看到程序成功输出了Hello, world!字符。

6. 进行debug

在vscode中对rust程序进行debug需要安装前面提到的CodeLLDB插件。首先在vscode的设置中设置Debug: Allow Breakpoints Everywhere。如下所示:

将main.rs文件内的代码修改为如下:

fn main() {

let _a = 3.0;

let _b = _a * _a;

println!("_b:{}", _b);

}

假设我们在第4行处打断点,如下图所示: 然后使用LLDB生成launch.json文件。按下ctrl+shift+p,打开vscode的命令输出栏目,输入 LLDB: Generate launch Configurations from Cargo.toml如下图所示: 按下回车后LLDB会根据Cargo.toml文件自动生成launch.json文件内容,此时文件名还是Untitled-1。我们需要将改文件保存到.vscode/目录下,并命名为launch.json(如果没有.vscode/文件夹,先手动在hello_world/目录下创建.vscode/文件夹)。LLDB自动生成的launch.json文件内容如下:

{

"version": "0.2.0",

"configurations": [

{

"type": "lldb",

"request": "launch",

"name": "Debug executable 'hello_world'",

"cargo": {

"args": [

"build",

"--bin=hello_world",

"--package=hello_world"

],

"filter": {

"name": "hello_world",

"kind": "bin"

}

},

"args": [],

"cwd": "${workspaceFolder}"

},

{

"type": "lldb",

"request": "launch",

"name": "Debug unit tests in executable 'hello_world'",

"cargo": {

"args": [

"test",

"--no-run",

"--bin=hello_world",

"--package=hello_world"

],

"filter": {

"name": "hello_world",

"kind": "bin"

}

},

"args": [],

"cwd": "${workspaceFolder}"

}

]

}

现在hello_world/目录下的文件结构如下: 之后点击vscode的状态栏的Debug excutabel 'hello_world' (hello_world)图标,并选择Debug executable 'hello_world'即可进行debug。 即下图红框中的图标: 可以看到程序成功运行到我们的断点处,并在左侧窗口中显示了中间变量的值。如下图所示:

四、参考

[1]. Rust in Visual Studio Code [2]. Hello, Cargo!

文章来源

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。