环境搭建
在开始学习 Rust 之前,我们需要先搭建好开发环境。本章将指导你完成 Rust 的安装、编辑器配置,并运行你的第一个 Rust 程序。
安装 Rust
Section titled “安装 Rust”Rust 官方推荐使用 rustup 来安装和管理 Rust 工具链。
macOS / Linux
Section titled “macOS / Linux”打开终端,运行以下命令:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh按照提示完成安装,然后重新加载环境变量:
source $HOME/.cargo/envWindows
Section titled “Windows”- 下载并运行 rustup-init.exe
- 按照安装向导完成安装
- 可能需要安装 Visual Studio C++ Build Tools
安装完成后,验证 Rust 是否安装成功:
rustc --versioncargo --version你应该能看到类似以下的输出:
rustc 1.75.0 (82e1608df 2023-12-21)cargo 1.75.0 (1d8b05cdd 2023-11-20)配置开发环境
Section titled “配置开发环境”VS Code(推荐)
Section titled “VS Code(推荐)”- 安装 Visual Studio Code
- 安装
rust-analyzer扩展(在扩展市场搜索安装)
rust-analyzer 提供了:
- 代码补全
- 类型提示
- 错误诊断
- 跳转定义
- 重构支持
- IntelliJ IDEA / CLion:安装 Rust 插件
- Vim / Neovim:配置 rust-analyzer LSP
- Sublime Text:安装 Rust Enhanced 插件
第一个程序:Hello World
Section titled “第一个程序:Hello World”使用 Cargo 创建项目
Section titled “使用 Cargo 创建项目”Cargo 是 Rust 的包管理器和构建工具,类似于 Node.js 的 npm 或 Python 的 pip。
# 创建新项目cargo new hello_rustcd hello_rust这会创建以下目录结构:
hello_rust/├── Cargo.toml # 项目配置文件└── src/ └── main.rs # 源代码入口查看生成的代码
Section titled “查看生成的代码”打开 src/main.rs,你会看到:
fn main() { println!("Hello, world!");}让我们理解这段代码:
fn main()定义了程序的入口函数println!是一个宏(注意末尾的!),用于打印文本到控制台- Rust 使用
{}来界定代码块,语句以;结尾
cargo run你应该看到输出:
Compiling hello_rust v0.1.0 (/path/to/hello_rust) Finished dev [unoptimized + debuginfo] target(s) in 0.50s Running `target/debug/hello_rust`Hello, world!Cargo 常用命令
Section titled “Cargo 常用命令”| 命令 | 说明 |
|---|---|
cargo new <name> | 创建新项目 |
cargo build | 编译项目(debug 模式) |
cargo build --release | 编译项目(release 模式,有优化) |
cargo run | 编译并运行 |
cargo check | 检查代码是否能编译(比 build 快) |
cargo test | 运行测试 |
cargo doc --open | 生成并打开文档 |
cargo update | 更新依赖 |
cargo check vs cargo build
Section titled “cargo check vs cargo build”cargo check 只检查代码能否编译,不生成可执行文件,速度比 cargo build 快很多。在开发过程中,建议频繁使用 cargo check 来检查代码。
# 快速检查代码cargo check
# 需要运行时才 buildcargo buildCargo.toml 详解
Section titled “Cargo.toml 详解”Cargo.toml 是项目的配置文件,使用 TOML 格式:
[package]name = "hello_rust"version = "0.1.0"edition = "2021"
[dependencies]# 在这里添加依赖name:项目名称version:项目版本edition:使用的 Rust 版本(2021 是目前最新的稳定版)[dependencies]:项目依赖
例如,添加 rand 随机数库:
[dependencies]rand = "0.8"然后运行 cargo build,Cargo 会自动下载并编译依赖。
练习 1:创建并运行项目
Section titled “练习 1:创建并运行项目”使用 cargo new 创建一个名为 my_first_rust 的项目,运行 Hello World 程序。
练习 2:修改程序
Section titled “练习 2:修改程序”修改 main.rs,让程序打印你的名字和今天的日期:
fn main() { println!("我是 [你的名字]"); println!("今天是 2024 年 1 月 1 日");}练习 3:体验 cargo check
Section titled “练习 3:体验 cargo check”- 故意在代码中引入一个错误(例如删掉一个分号)
- 运行
cargo check,观察错误信息 - 运行
cargo build,比较两者的输出和速度 - 修复错误,再次运行
思考:为什么开发时推荐使用 cargo check 而不是 cargo build?
环境搭建完成后,让我们进入下一章,学习 Rust 的基本语法。