Skip to content

环境自检与练习工程

学习路线定了目标之后,先把环境验一遍、把练习工程的目录习惯立起来; 最后附一张从旧语言迁移 Rust 的成本对照表与起步命令速查。

环境自检:一条命令确认一切就绪

Windows + PowerShell 下,把下面整段贴进终端执行。

powershell
# 一次性检查 Rust 工具链是否完备
Write-Host "== 版本 ==" -ForegroundColor Cyan
rustc --version
cargo --version
rustup --version

Write-Host "`n== 默认工具链与目标平台 ==" -ForegroundColor Cyan
rustup show

Write-Host "`n== 组件(需要 rustfmt / clippy / rust-analyzer)==" -ForegroundColor Cyan
rustup component list --installed

Write-Host "`n== 编译一个临时程序验证工具链可用 ==" -ForegroundColor Cyan
$tmp = Join-Path $env:TEMP "rust_smoke_check"
New-Item -ItemType Directory -Force -Path $tmp | Out-Null
Set-Content -Path (Join-Path $tmp "main.rs") -Value @'
fn main() {
    let name = "Rust 2024";
    println!("hello, {name}!");
}
'@ -Encoding utf8
Push-Location $tmp
cargo init --name smoke_check --vcs none 2>$null | Out-Null
cargo run --quiet
Pop-Location
Remove-Item -Recurse -Force $tmp

期望输出包含:

rustc 1.98.1 (48a229cea 2026-09-01)
cargo 1.98.1 (797e8a9bc 2026-08-05)
...
hello, Rust 2024!

如果你看到 hello, Rust 2024!,说明工具链已经能编译、能运行、中文输出正常。

💡 说明:上面用 cargo init%TEMP% 下建临时工程再删除,不弄乱你现有的目录。后续各章的练习请自己建工程(见下一节)。

缺少组件时

powershell
rustup component add rustfmt clippy rust-analyzer rust-docs
  • rustfmt:格式化(相当于 Python 的 black、JS 的 prettier
  • clippy:lint(相当于 eslint / pylint,但更强)
  • rust-analyzer:编辑器语言服务(补全、跳转、内联类型提示)
  • rust-docs:离线标准库文档,用 rustup doc 打开

路径相关提醒

  • Windows 上默认工具链是 stable-x86_64-pc-windows-msvc,即使用 MSVC 链接器,需要 Visual Studio Build Tools(含「使用 C++ 的桌面开发」)。缺它会在链接阶段报 link.exe not found,安装方式见〈环境搭建与工具链〉一章
  • 不要把工程放在含中文或空格的深路径下(例如桌面同步目录),老版本工具链在长路径上偶有怪异问题。建议放在纯 ASCII 的简短路径(如 D:\rust)。


练习工程的组织方式

练习代码建议放在单独的目录里,例如一个 rust-practice 目录:

powershell
mkdir rust-practice
cd rust-practice
cargo new ch03_ownership      # 〈所有权〉一章练习
cargo new ch04_traits         # 〈结构体与 trait〉一章练习

或者只为每章建一个工程,用多个 bin 目标放不同练习:

rust-practice/ch03_ownership/
├── Cargo.toml
└── src/
    ├── bin/
    │   ├── ex1_fix_move.rs       # cargo run --bin ex1_fix_move
    │   └── ex2_longest.rs        # cargo run --bin ex2_longest
    └── lib.rs

src/bin/*.rs 里的每个文件都会自动成为一个可执行目标,非常适合做「一题一文件」。

🧠 原理Cargo.toml[[bin]] 默认约定是 src/main.rssrc/bin/ 下的所有 .rs。用 cargo run --bin <名字> 指定跑哪一个;不加 --bin 时若有多个目标,cargo 会报错要求你选。



与其他语言的对照:学习成本迁移表

你在旧语言里的能力迁移到 Rust 时的变化
变量赋值let a = b; 可能移动 b,之后 b 不可用(Copy 类型除外)
传参默认是移动或不可变借用,想改必须显式 &mut
对象引用同一时刻要么多个只读借用,要么一个可写借用,不能兼得
null不存在;用 Option<T> 显式建模「可能没有」
异常不存在;用 Result<T, E> + ? 显式传播
接口/抽象类trait(可带默认实现),无继承
泛型同样是编译期展开,但无类型擦除、无装箱开销
反射基本没有;改用宏(〈宏〉一章)或 trait
线程共享数据必须用 Arc<Mutex<T>> 之类显式证明安全,否则编译不过


速查表:常用起步命令

目的命令
新建可执行工程cargo new myapp
新建库工程cargo new --lib mylib
在当前目录初始化cargo init
编译并运行cargo run
只做类型检查(最快反馈)cargo check
发布构建cargo build --release
运行测试cargo test
格式化cargo fmt
lintcargo clippy -- -D warnings
生成并打开文档cargo doc --open
添加依赖cargo add serde --features derive
查看依赖树cargo tree
解释错误码cargo explain E0502
打开离线标准库文档rustup doc

内容以 rustc 1.98.1 · Rust 2024 edition 为基准