windows下 Rust 环境配置
阅读原文时间:2023年07月08日阅读:1

首先,需要安装最新版的 Rust 编译工具和 Visual Studio Code。

Rust 编译工具:https://www.rust-lang.org/zh-CN/tools/install

Visual Studio Code:https://code.visualstudio.com/Download

Rust 安装:https://www.rust-lang.org/zh-CN/tools/install

C++构建工具:https://visualstudio.microsoft.com/zh-hans/visual-cpp-build-tools/

Rust 的编译工具依赖 C 语言的编译工具,这意味着你的电脑上至少已经存在一个 C 语言的编译环境。如果你使用的是 Linux 系统,往往已经具备了 GCC 或 clang。如果你使用的是 macOS,需要安装 Xcode。如果你是用的是 Windows 操作系统,你需要安装 Visual Studio 2013 或以上的环境(需要 C/C++ 支持)以使用 MSVC 或安装 MinGW + GCC 编译环境(Cygwin 还没有测试)。

安装 Rust 编译工具

安装初始向导

如果没有Visual Studio环境使用1进行快速安装(并不是所有的机器都会自动安装,如果提示没有环境,需要手动安装msvc开发环境)

安装完成后会进入如下的界面,按1继续安装,接下来这个向导会自动安装rust和cargo包管理器

安装成功后可以使用rustc -V 来查看rust版本,如下图所示,已经安装完成

配置VS code环境

安装rust-analyzer、Native Debug、C/C++

重新启动 VSCode,Rust 的开发环境就搭建好了。

第一个rust应用

$ cargo new hello_world
$ cd hello_world

项目结构

├─.gitignore
├─Cargo.toml
├─result.txt
├─src
|  └main.rs

运行

cargo run

运行结果

$ cargo run
   Compiling hello_world v0.1.0 (F:\项目\rust-demo\hello_world)
    Finished dev [unoptimized + debuginfo] target(s) in 0.26s
     Running `target\debug\hello_world.exe`
Hello, world!

上述代码,cargo run 首先对项目进行编译,然后再运行,因此它实际上等同于运行了两个指令,下面我们手动试一下编译和运行项目:

编译

$ cargo build
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s

运行

$ ./target/debug/world_hello
Hello, world!

但是上述也只是debug模式下的编译,发布版本release应该这样做吗,添加 --release来编译:

  • cargo run --release
  • cargo build --release

使用 release 编译会比默认的 debug 编译性能提升 10 倍以上,但是 release 缺点是编译速度较慢,而且不会显示 panic backtrace 的具体行号