强曰为道
与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

Rust 系统编程语言完全教程 / 第02章:安装与环境配置

第02章:安装与环境配置

2.1 rustup:Rust 工具链管理器

什么是 rustup

rustup 是 Rust 官方的工具链安装和管理工具,类似 Python 的 pyenv 或 Node.js 的 nvm。它负责:

  • 安装和更新 Rust 编译器(rustc
  • 管理多个 Rust 版本(stable、beta、nightly)
  • 安装交叉编译目标
  • 管理组件(rustfmt、clippy 等)

安装 rustup

Linux / macOS:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

安装过程中会提示选择安装类型,建议选择默认选项 1(Proceed with standard installation)。

Windows:

  1. 访问 https://rustup.rs
  2. 下载并运行 rustup-init.exe
  3. 按提示完成安装(需要先安装 Visual Studio C++ 构建工具)

验证安装:

rustc --version
# rustc 1.XX.0 (xxxxxxx YYYY-MM-DD)

cargo --version
# cargo 1.XX.0 (xxxxxxx YYYY-MM-DD)

rustup --version
# rustup 1.XX.0 (xxxxxxx YYYY-MM-DD)

rustup 常用命令

命令说明
rustup update更新所有已安装的工具链
rustup default stable设置默认工具链为 stable
rustup install nightly安装 nightly 版本
rustup target list列出可用的编译目标
rustup target add wasm32-unknown-unknown添加 WebAssembly 目标
rustup component add rustfmt添加格式化工具
rustup component add clippy添加 lint 工具
rustup show显示当前工具链信息
rustup self uninstall卸载 Rust

管理多个工具链

# 安装不同版本
rustup install stable
rustup install beta
rustup install nightly

# 查看已安装的工具链
rustup toolchain list

# 切换默认版本
rustup default nightly

# 为某个项目固定版本(在项目目录下)
rustup override set stable

注意: 大多数生产项目使用 stable 版本。nightly 版本包含实验性功能,适合尝试新特性或需要特定 nightly-only 功能时使用。


2.2 Cargo 配置

Cargo 配置文件

Cargo 的全局配置文件位于:

操作系统路径
Linux / macOS~/.cargo/config.toml
Windows%USERPROFILE%\.cargo\config.toml

常用配置项

# ~/.cargo/config.toml

[build]
# 使用国内镜像加速编译(利用 sccache)
# rustflags = ["-C", "link-arg=-fuse-ld=lld"]  # 使用 lld 加速链接

[net]
# 设置网络超时(秒)
git-fetch-with-cli = true

[registries.crates-io]
# 使用国内镜像(推荐)
protocol = "sparse"

[source.crates-io]
replace-with = "ustc"  # 使用中科大镜像

[source.ustc]
registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"

# 或者使用字节跳动镜像
# [source.rsproxy]
# registry = "sparse+https://rsproxy.cn/crates.io-index/"

国内镜像推荐

镜像源地址说明
中科大https://mirrors.ustc.edu.cn/crates.io-index/稳定
字节跳动https://rsproxy.cn/crates.io-index/速度快
清华大学https://mirrors.tuna.tsinghua.edu.cn/crates.io-index/稳定

注意: 从 Rust 1.70+ 开始,推荐使用 sparse 协议(sparse+https://...),比 git 协议更快。


2.3 环境变量

PATH 配置

安装 rustup 后,以下路径会自动添加到 PATH

# Cargo 二进制目录
export PATH="$HOME/.cargo/bin:$PATH"

如果安装后命令不可用,手动将上述行添加到 ~/.bashrc~/.zshrc

常用环境变量

变量说明示例
RUSTUP_HOMErustup 数据目录~/.rustup
CARGO_HOMECargo 数据目录~/.cargo
RUSTFLAGS全局编译选项-C target-cpu=native
RUST_LOG日志级别(env_logger)debug
RUST_BACKTRACE错误时显示回溯1full

2.4 IDE 配置

VS Code(推荐)

VS Code 是 Rust 开发最流行的 IDE,配合 rust-analyzer 插件提供出色的开发体验。

安装步骤:

  1. 安装 VS Code
  2. 打开扩展面板(Ctrl+Shift+X
  3. 搜索并安装 rust-analyzer

推荐插件列表:

插件说明
rust-analyzerRust 语言服务器,提供智能补全、类型提示等
Even Better TOMLCargo.toml 语法高亮和验证
Error Lens内联显示错误信息
CodeLLDB调试器(支持断点、变量查看)
crates显示 Cargo.toml 中依赖的最新版本
Dependi依赖版本管理辅助

VS Code 设置(.vscode/settings.json):

{
    "rust-analyzer.check.command": "clippy",
    "rust-analyzer.cargo.features": "all",
    "rust-analyzer.inlayHints.chainingHints.enable": true,
    "rust-analyzer.inlayHints.typeHints.enable": true,
    "rust-analyzer.inlayHints.parameterHints.enable": true,
    "editor.formatOnSave": true,
    "[rust]": {
        "editor.defaultFormatter": "rust-lang.rust-analyzer"
    }
}

JetBrains RustRover

JetBrains 提供的专用 Rust IDE(已取代 IntelliJ Rust 插件):

  1. 下载 RustRover
  2. 安装后打开 Rust 项目
  3. 自动配置 rust 工具链
特性VS Code + rust-analyzerRustRover
价格免费免费(非商业)
内存占用较低较高
代码补全优秀优秀
调试CodeLLDB内置
重构能力一般强大
启动速度较慢

Neovim / Helix

终端用户的选择:

-- Neovim LSP 配置示例(使用 lspconfig)
local lspconfig = require('lspconfig')
lspconfig.rust_analyzer.setup({
    settings = {
        ['rust-analyzer'] = {
            checkOnSave = {
                command = 'clippy',
            },
        },
    },
})

2.5 rust-analyzer 详解

工作原理

rust-analyzer 是一个增量式的 Rust 语言服务器(Language Server),它:

  1. 实时解析项目代码
  2. 构建内存中的项目模型
  3. 通过 LSP 协议向编辑器提供功能

核心功能

功能快捷键(VS Code)说明
跳转到定义F12跳转到符号定义处
查找引用Shift+F12查找所有使用该符号的地方
重命名符号F2安全地重命名变量/函数等
自动导入自动添加 use 语句
内联提示显示推断的类型和参数名
代码动作Ctrl+.快速修复和重构
悬停文档悬停鼠标显示类型和文档
补全Ctrl+Space智能代码补全

配置详解

在 VS Code 的 settings.json 中配置 rust-analyzer:

{
    // 检查命令:使用 clippy 代替默认的 cargo check
    "rust-analyzer.check.command": "clippy",

    // 启用所有 cargo features
    "rust-analyzer.cargo.features": "all",

    // 链式调用的类型提示
    "rust-analyzer.inlayHints.chainingHints.enable": true,

    // 类型注解提示
    "rust-analyzer.inlayHints.typeHints.enable": true,

    // 参数名提示
    "rust-analyzer.inlayHints.parameterHints.enable": true,

    // 保存时自动格式化
    "editor.formatOnSave": true,

    // proc-macro 支持
    "rust-analyzer.procMacro.enable": true
}

2.6 验证环境

创建一个测试项目验证环境配置:

# 创建新项目
cargo new test_env
cd test_env

# 编译并运行
cargo run

# 运行 clippy 检查
cargo clippy

# 格式化代码
cargo fmt

# 运行测试
cargo test

预期输出:

   Compiling test_env v0.1.0 (/path/to/test_env)
    Finished dev [unoptimized + debuginfo] target(s) in 0.50s
     Running `target/debug/test_env`
Hello, world!

环境检查清单

检查项命令预期结果
Rust 编译器rustc --versionrustc 1.XX.0
Cargocargo --versioncargo 1.XX.0
rustuprustup show显示当前工具链
clippycargo clippy --version显示版本
rustfmtcargo fmt --version显示版本
编译运行cargo run输出 “Hello, world!”
测试cargo test测试通过

2.7 常见问题排查

编译很慢

# 使用 mold 链接器(Linux)
# 安装 mold: sudo apt install mold 或从源码编译
# 在 .cargo/config.toml 中配置:
[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "link-arg=-fuse-ld=mold"]

# 或使用 lld
[target.x86_64-unknown-linux-gnu]
rustflags = ["-C", "link-arg=-fuse-ld=lld"]

# 启用增量编译(默认开启)
export CARGO_INCREMENTAL=1

# 使用 sccache 缓存编译结果
cargo install sccache
export RUSTC_WRAPPER=sccache

下载依赖失败

# 检查网络配置
cargo config get net

# 使用镜像源(见 2.2 节)

# 使用 git 命令代替 libgit2
export CARGO_NET_GIT_FETCH_WITH_CLI=true

rust-analyzer 不工作

# 确认 rust-analyzer 已安装
rustup component list | grep rust-analyzer

# 手动安装
rustup component add rust-analyzer

# 在 VS Code 中重启语言服务器
# Ctrl+Shift+P → "rust-analyzer: Restart server"

2.8 本章小结

要点说明
rustupRust 官方工具链管理器,支持多版本切换
Cargo 配置~/.cargo/config.toml,可配置镜像源和编译选项
rust-analyzer语言服务器,提供代码补全、跳转等 IDE 功能
推荐 IDEVS Code + rust-analyzer 或 JetBrains RustRover
镜像加速推荐使用中科大或字节跳动镜像

扩展阅读

  1. rustup 官方文档 — 工具链管理详细指南
  2. Cargo 配置文档 — 所有配置项说明
  3. rust-analyzer 手册 — 配置和故障排查
  4. Rust 性能优化编译技巧 — 加速编译的方法