rustup 是 Rust 官方的工具链管理器,负责安装、升级和切换 Rust 工具链(rustc、cargo、rustfmt、clippy 等)。它类似于 Python 的 pyenv、Node 的 nvm,是 Rust 开发的标准入口。

安装

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

安装后工具链放在 ~/.rustup/toolchains/cargorustc 等命令实际是 ~/.cargo/bin/ 下的 rustup 代理(proxy),由 rustup 根据当前配置转发到具体工具链。

卸载:

1
rustup self uninstall

工具链管理

工具链(toolchain)由「通道 + 版本 + 目标平台」构成,如 stable-x86_64-apple-darwin1.75.0nightly-2024-01-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 查看已安装的工具链
rustup toolchain list

# 安装 stable / beta / nightly 通道
rustup toolchain install stable
rustup toolchain install nightly

# 安装指定版本
rustup toolchain install 1.75.0

# 安装某天的 nightly(配合 ci 场景复现)
rustup toolchain install nightly-2024-06-01

# 卸载
rustup toolchain uninstall nightly-2024-06-01

设置默认工具链

1
2
rustup default stable
rustup default nightly

临时切换工具链

1
2
3
4
5
6
7
# 单条命令使用指定工具链
cargo +nightly build
rustup run nightly cargo build

# 对当前目录设置覆盖(override),优先级高于 default
rustup override set nightly
rustup override unset

rust-toolchain.toml

项目内通过配置文件固定工具链,团队成员和 CI 自动使用同一版本:

1
2
3
4
[toolchain]
channel = "1.78.0"
components = ["rustfmt", "clippy"]
targets = ["wasm32-unknown-unknown"]

rustup 进入该目录时自动检测并按需安装。也可用纯文本的 rust-toolchain 文件(只写通道名,如 nightly),但推荐使用 toml 格式。

优先级从高到低:命令行 +toolchain > 目录 override > rust-toolchain.toml > rustup default

组件管理

1
2
3
4
5
6
7
8
9
10
# 查看组件状态
rustup component list

# 常用组件
rustup component add rustfmt # 格式化
rustup component add clippy # lint
rustup component add rust-src # 源码(rust-analyzer、-Z build-std 需要)
rustup component add rust-analyzer

rustup component remove clippy

交叉编译目标

1
2
3
4
5
6
7
8
# 查看所有目标
rustup target list

# 添加目标并交叉编译
rustup target add x86_64-unknown-linux-musl
cargo build --target x86_64-unknown-linux-musl

rustup target remove wasm32-unknown-unknown

升级与更新

1
2
3
4
5
6
7
8
9
10
11
# 更新所有已安装的工具链(及 rustup 自身)
rustup update

# 只更新某个工具链
rustup update stable

# 只更新 rustup 自身
rustup self update

# 检查更新但不安装
rustup check

常用查询

1
2
3
4
5
rustup show            # 当前生效的工具链、target、组件一览
rustup which rustc # 定位实际二进制路径
rustup doc # 浏览器打开本地离线文档
rustup doc --std # 标准库文档
rustup man cargo # 查看 man 手册

国内加速

官方源较慢时可使用镜像(以中科大为例):

1
2
3
export RUSTUP_DIST_SERVER="https://mirrors.ustc.edu.cn/rust-static"
export RUSTUP_UPDATE_ROOT="https://mirrors.ustc.edu.cn/rust-static/rustup"
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

crates.io 的加速则需在 ~/.cargo/config.toml 中配置 source 替换,与 rustup 无关。

代理机制说明

~/.cargo/bin 下的 cargorustcrustdoc 等都是 rustup 的硬链接/副本。执行时 rustup 按上述优先级解析出应使用的工具链,再调用 ~/.rustup/toolchains/<toolchain>/bin/ 下真正的二进制。因此:

  • 不要把 ~/.rustup/toolchains/*/bin 直接加进 PATH,会绕过版本解析;
  • IDE(如 rust-analyzer)通过 rustup which 或直接走代理即可自动跟随项目配置。