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/,cargo、rustc 等命令实际是 ~/.cargo/bin/ 下的 rustup 代理(proxy),由 rustup 根据当前配置转发到具体工具链。
卸载:
工具链管理
工具链(toolchain)由「通道 + 版本 + 目标平台」构成,如 stable-x86_64-apple-darwin、1.75.0、nightly-2024-01-01。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| rustup toolchain list
rustup toolchain install stable rustup toolchain install nightly
rustup toolchain install 1.75.0
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
rustup override set nightly rustup override unset
|
项目内通过配置文件固定工具链,团队成员和 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 rustup component add rust-src 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 update
rustup update stable
rustup self update
rustup check
|
常用查询
1 2 3 4 5
| rustup show rustup which rustc rustup doc rustup doc --std rustup man cargo
|
国内加速
官方源较慢时可使用镜像(以中科大为例):
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 下的 cargo、rustc、rustdoc 等都是 rustup 的硬链接/副本。执行时 rustup 按上述优先级解析出应使用的工具链,再调用 ~/.rustup/toolchains/<toolchain>/bin/ 下真正的二进制。因此:
- 不要把
~/.rustup/toolchains/*/bin 直接加进 PATH,会绕过版本解析; - IDE(如 rust-analyzer)通过
rustup which 或直接走代理即可自动跟随项目配置。