Skip to content

工具链

> 掌握现代 Rust 开发工具链。

rustup - Rust 版本管理器

安装与配置

bash
# 安装 rustup(如果尚未安装)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# 更新到最新版本
rustup update

# 查看当前版本
rustup --version
rustc --version
cargo --version

工具链管理

bash
# 查看已安装的工具链
rustup show

# 安装特定版本
rustup install 1.75.0
rustup install stable
rustup install beta
rustup install nightly

# 设置默认工具链
rustup default stable
rustup default nightly

# 按项目设置工具链
cd my_project
rustup override set nightly  # 该目录使用 nightly
rustup override unset        # 清除覆盖设置

工具链组件

bash
# 查看已安装组件
rustup component list --installed

# 安装组件
rustup component add clippy      # Lint 工具
rustup component add rustfmt    # 格式化工具
rustup component add rust-src    # 源代码(用于 IDE)
rustup component add rust-analyzer # LSP 服务器
rustup component add llvm-tools  # LLVM 工具

# 查看可用组件
rustup component list

目标平台

bash
# 查看已安装目标
rustup target list --installed

# 添加编译目标
rustup target add x86_64-pc-windows-gnu
rustup target add wasm32-unknown-unknown
rustup target add aarch64-apple-darwin

# 交叉编译
cargo build --target x86_64-pc-windows-gnu

cargo - Rust 包管理器

基本命令

bash
# 创建项目
cargo new my_project          # 二进制项目
cargo new --lib my_lib        # 库项目

# 构建项目
cargo build                   # Debug 构建
cargo build --release         # Release 构建
cargo check                   # 快速检查(不生成二进制)

# 运行项目
cargo run                     # 运行 Debug 构建
cargo run --release           # 运行 Release 构建
cargo run -- --arg1 arg2      # 传递参数

# 测试
cargo test                    # 运行所有测试
cargo test test_name          # 运行特定测试
cargo test -- --nocapture     # 显示测试输出
cargo test -- --test-threads=1  # 单线程运行测试

# 文档
cargo doc                     # 生成文档
cargo doc --open               # 生成并打开文档
cargo doc --no-deps           # 不生成依赖文档

依赖管理

bash
# 添加依赖
cargo add serde               # 添加最新版本
cargo add serde@1.0           # 指定版本
cargo add tokio --features full  # 指定特性

# 移除依赖
cargo rm serde

# 更新依赖
cargo update                  # 更新所有依赖
cargo update -p serde         # 更新特定依赖

# 查看依赖树
cargo tree                    # 显示依赖树
cargo tree -d                 # 显示重复依赖
cargo tree --invert serde     # 查看谁依赖 serde

高级命令

bash
# Clippy - Lint 检查
cargo clippy                  # 运行 clippy
cargo clippy -- -W clippy::all  # 所有警告
cargo clippy --fix            # 自动修复

# 格式化
cargo fmt                     # 格式化代码
cargo fmt -- --check          # 检查格式

# 安全审计
cargo audit                   # 检查安全漏洞

# 基准测试
cargo bench                   # 运行基准测试

# 发布
cargo publish                 # 发布到 crates.io
cargo yank --vers 1.0.0       # 撤回版本

Cargo.toml 配置

toml
[package]
name = "my_project"
version = "0.1.0"
edition = "2024"
authors = ["Your Name <you@example.com>"]
description = "A sample project"
license = "MIT"
repository = "https://github.com/user/my_project"
keywords = ["rust", "example"]
categories = ["command-line-utilities"]

[dependencies]
# 基本依赖
serde = "1.0"

# 指定特性
tokio = { version = "1.0", features = ["full"] }

# 可选依赖
rand = { version = "0.8", optional = true }

# 开发依赖
[dev-dependencies]
tokio-test = "0.4"

# 构建依赖
[build-dependencies]
cc = "1.0"

[features]
default = ["std"]
std = []
extra = ["rand"]

[profile.release]
opt-level = 3          # 优化等级
lto = true             # 链接时优化
codegen-units = 1      # 代码生成单元
strip = true           # 剥离符号信息

[profile.dev]
opt-level = 0          # 不优化
debug = true           # 包含调试信息

rust-analyzer - IDE 支持

VS Code 配置

json
// .vscode/settings.json
{
  "rust-analyzer.cargo.features": "all",
  "rust-analyzer.checkOnSave.command": "clippy",
  "rust-analyzer.completion.postfix.enable": true,
  "rust-analyzer.inlayHints.parameterHints.enable": true,
  "rust-analyzer.inlayHints.typeHints.enable": true,
  "rust-analyzer.lens.enable": true,
  "rust-analyzer.lens.implementations.enable": true,
  "rust-analyzer.lens.references.enable": true,
  "rust-analyzer.procMacro.enable": true,
  "rust-analyzer.cargo.buildScripts.enable": true
}

扩展推荐

json
// VS Code 扩展
{
  "recommendations": [
    "rust-lang.rust-analyzer",     // Rust 语言服务器
    "vadimcn.vscode-lldb",         // 调试支持
    "serayuzgur.crates",           // crates.io 支持
    "tamasfe.even-better-toml",    // TOML 支持
    "swellaby.vscode-rust-test-adapter"  // 测试适配器
  ]
}

rust-analyzer 功能

内联提示:

rust
// rust-analyzer 会显示类型提示
let x = 42;           // : i32
let s = "hello";      // : &str
let v = vec![1, 2, 3]; // : Vec<i32>

fn process(data: &[u8]) -> Result<String, Error> {
    //                ^^^^^^^^^^^^^^^^^^^^^^
    //                显示返回类型
}
▶ Run

代码操作(Code Actions):

rust
// 光标放在未使用的导入上
use std::collections::HashMap;  // 💡 快速修复:移除未使用的导入

// 光标放在函数上
fn my_function() {  // 💡 添加文档注释
                     // 💡 生成实现
}
▶ Run

重构支持:

rust
// 提取函数
let sum = a + b + c;
// 选中后:💡 提取为函数

// 内联变量
let x = 42;
let y = x + 8;
// 光标在 x 上:💡 内联变量
▶ Run

调试工具

调试配置

json
// .vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "lldb",
      "request": "launch",
      "name": "Debug",
      "cargo": {
        "args": [
          "build",
          "--bin=my_project",
          "--package=my_project"
        ],
        "filter": {
          "name": "my_project",
          "kind": "bin"
        }
      },
      "args": [],
      "cwd": "${workspaceFolder}"
    },
    {
      "type": "lldb",
      "request": "launch",
      "name": "Debug Tests",
      "cargo": {
        "args": [
          "test",
          "--no-run",
          "--lib",
          "--package=my_project"
        ],
        "filter": {
          "name": "my_project",
          "kind": "lib"
        }
      }
    }
  ]
}

调试断言

rust
// 使用断言调试
fn process(value: i32) -> i32 {
    debug_assert!(value >= 0, "value must be non-negative");
    debug_assert!(value < 100, "value must be less than 100");
    
    // 在 Debug 构建中会检查
    // 在 Release 构建中被移除
    value * 2
}

// 使用 assert! 进行运行时检查
fn process_runtime(value: i32) -> i32 {
    assert!(value >= 0, "value must be non-negative");
    // 所有构建都会检查
    value * 2
}
▶ Run

性能分析

性能分析工具

bash
# 生成火焰图(需要 cargo-flamegraph)
cargo flamegraph --bin my_project

# 基准测试
cargo bench

# 内存分析(使用 valgrind)
valgrind --tool=massif target/release/my_project

# 二进制大小分析
cargo bloat --release
cargo bloat --release --crates

性能测试示例

rust
// benches/my_bench.rs
use criterion::{black_box, criterion_group, criterion_main, Criterion};

fn fibonacci(n: u64) -> u64 {
    match n {
        0 => 1,
        1 => 1,
        n => fibonacci(n - 1) + fibonacci(n - 2),
    }
}

fn criterion_benchmark(c: &mut Criterion) {
    c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20))));
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
▶ Run

工作流示例

开发工作流

bash
# 1. 创建新项目
cargo new my_project && cd my_project

# 2. 设置版本
rustup override set stable

# 3. 添加依赖
cargo add serde --features derive
cargo add tokio --features full

# 4. 开发循环
cargo check        # 快速检查
cargo test         # 运行测试
cargo clippy       # Lint 检查
cargo fmt          # 格式化

# 5. 发布准备
cargo build --release
cargo test --release
cargo clippy --release

CI/CD 配置

yaml
# .github/workflows/ci.yml
name: CI

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Install Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          components: clippy, rustfmt
          
      - name: Check formatting
        run: cargo fmt -- --check
        
      - name: Run clippy
        run: cargo clippy -- -D warnings
        
      - name: Run tests
        run: cargo test --verbose
        
      - name: Build release
        run: cargo build --release

最佳实践

1. 定期更新

bash
# 每周运行
rustup update        # 更新 Rust
cargo update         # 更新依赖
cargo audit          # 安全检查

2. 使用 Justfile

just
# justfile
build:
    cargo build

test:
    cargo test

lint:
    cargo clippy -- -D warnings
    cargo fmt -- --check

run:
    cargo run

release:
    cargo build --release
bash
# 安装 just
cargo install just

# 使用
just build
just test

3. 项目结构

my_project/
├── Cargo.toml
├── Cargo.lock
├── .gitignore
├── .vscode/
│   ├── settings.json
│   └── launch.json
├── src/
│   ├── main.rs
│   └── lib.rs
├── tests/
│   └── integration_test.rs
├── benches/
│   └── my_bench.rs
└── examples/
    └── example.rs

小结

现代 Rust 工具链核心:

工具用途关键命令
rustup版本管理rustup update, rustup default
cargo包管理cargo build, cargo test, cargo clippy
rust-analyzerIDE 支持自动补全、类型提示、重构
clippyLint 检查cargo clippy
rustfmt代码格式化cargo fmt

高效工作流:

  1. 使用 cargo check 快速验证
  2. 使用 cargo clippy 提高代码质量
  3. 使用 cargo fmt 统一代码风格
  4. 使用 rust-analyzer 提升 IDE 体验
  5. 使用 CI/CD 自动化测试和发布

下一步: 下一节我们将学习如何从旧 Edition 迁移到 Rust 2024。

练习

练习 1:工具链设置

配置完整的开发环境:

bash
# TODO: 安装 rustup
# TODO: 安装组件(clippy, rustfmt, rust-analyzer)
# TODO: 配置 VS Code

练习 2:项目配置

创建一个新项目并配置:

bash
# TODO: 创建项目
# TODO: 添加依赖(serde, tokio, clap)
# TODO: 配置 Cargo.toml(特性、profile)
# TODO: 创建 Justfile

练习 3:CI/CD

为项目配置 CI/CD:

yaml
# TODO: 创建 GitHub Actions 工作流
# TODO: 配置测试、lint、构建步骤