#工作记录
WSL 中 Rust 安装与测试完整记录
1. 运行环境
- 系统:Ubuntu 24.04 LTS (WSL2)
- 架构:x86_64 (GNU/Linux)
- Rust 版本:rustc 1.87.0 (2025-05-09)
- Cargo 版本:cargo 1.87.0 (2025-05-06)
2. 安装 Rust
2.1 使用 Rust 官方安装脚本
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
- Rustup 是 Rust 官方推荐的版本管理工具,可以安装多个 Rust 版本并切换。
- 安装位置:
Rustup
数据存储在/home/用户名/.rustup
Cargo
(Rust 包管理器)存储在/home/用户名/.cargo
Rust
工具链(编译器rustc
,包管理器cargo
,格式化工具rustfmt
,Lint 解析工具clippy
)都安装在/home/用户名/.cargo/bin
2.2 选择安装选项
安装脚本会提供选项:
1) Proceed with standard installation (default)
2) Customize installation
3) Cancel installation
选择 1 进行标准安装。
2.3 安装过程
Rustup 会自动:
- 同步最新的 Rust 版本(Stable 1.87.0)。
- 下载和安装 Rust 相关组件:
- Cargo(包管理器)
- Clippy(代码检查工具)
- Rust Docs(文档)
- Rust 标准库 (
rust-std
) - Rust 编译器 (
rustc
) - Rustfmt(格式化工具)
3. 配置环境变量
安装完成后,需要更新 PATH
以让系统识别 cargo
和 rustc
:
source ~/.bashrc
或:
. "$HOME/.cargo/env"
验证 Rust 版本:
rustc --version # rustc 1.87.0 (2025-05-09)
cargo --version # cargo 1.87.0 (2025-05-06)
4. 创建 Rust 项目
使用 cargo new
创建项目:
cargo new hello_rust
会生成:
hello_rust/
├── Cargo.toml # 项目配置文件(依赖管理)
└── src/
└── main.rs # 入口文件
4.1 处理已有目录
如果 cargo new hello_rust
报错(因为运行了两次cargo new hello_rust命令导致):
error: destination `/home/love/hello_rust` already exists
表示该目录已存在,可以改用:
cargo init hello_rust
这样 Cargo 会初始化一个现有目录,使其成为 Rust 项目,而不会创建重复的文件。
4.2 查看项目结构
可以安装 tree
来更清晰地查看目录结构:
sudo apt install tree
然后运行:
tree hello_rust
我们应该看到:
hello_rust
├── Cargo.lock
├── Cargo.toml
├── src
│ └── main.rs
└── target
4.3 进入项目目录
cd hello_rust
4.4 编辑 main.rs
使用 nano
编辑 src/main.rs
:
nano src/main.rs
写入:
fn main() {
println!("Hello, world!");
}
然后 保存并退出(Ctrl + X
→ Y
→ Enter
)。
5. 编译和运行 Rust 程序
5.1 编译
cargo build
编译完成后,会在 target/debug/
下生成可执行文件。
5.2 运行
cargo run
成功的话,我们会看到:
Hello, world!
6. 其他 Rust 命令
6.1 检查代码
cargo check
这会进行语法检查,但不会生成二进制文件。
6.2 格式化代码
cargo fmt
自动格式化 .rs
文件。
6.3 运行代码 Lint 检查
cargo clippy
提供代码优化建议。
7. 总结
✅ 安装 Rust 成功 (rustc 1.87.0
)
✅ Rust 配置正确 (cargo
可用)
✅ 初始化现有 Rust 目录 (cargo init hello_rust
)
✅ 安装 tree
后可以正确查看项目结构
✅ 成功编译并运行 Hello, World!
程序
🎉 我们的 WSL Rust 开发环境已成功搭建,可以开始写代码了!🚀