Ubuntu 上升级 Rust 的推荐方法
在 Ubuntu 上,升级 Rust 的推荐方式是使用官方的 rustup 工具链管理器;若你是通过系统仓库(apt)安装的 rustc/cargo,也可以升级系统包或迁移到 rustup 以获得更快、更灵活的更新与多版本管理。
使用 rustup 升级(推荐)
- 1)安装或确保已安装 rustup(如尚未安装):
- 安装依赖:sudo apt update && sudo apt install -y curl build-essential gcc make
- 安装 rustup:curl --proto ‘=https’ --tlsv1.2 -sSf https://sh.rustup.rs | sh
- 使环境变量生效:source $HOME/.cargo/env
- 2)查看当前工具链与生效版本:rustup show
- 3)升级到最新稳定版:rustup update
- 4)如需切换到其他通道或版本:rustup default stable|beta|nightly;或安装指定版本:rustup update 1.85.0
- 5)验证版本:rustc -V、cargo -V
- 6)仅升级工具组件(不换版本):rustup component update rustc cargo clippy rustfmt
- 7)卸载(如需):rustup self uninstall
以上命令覆盖日常升级、版本切换与组件维护。
从 APT 升级或迁移到 rustup
- 1)查看当前 APT 安装的版本:which rustc;rustc -Vv(常见路径为 /usr/bin/rustc)
- 2)升级系统包:sudo apt update && sudo apt install --only-upgrade rustc cargo
- 3)APT 通常版本较旧(例如 Ubuntu 22.04 仓库常见为 1.61),若需新特性/更快更新,建议迁移到 rustup(见上节)。迁移前可先备份项目,再按需卸载 APT 版:sudo apt remove rustc cargo
- 4)若之前通过 APT 安装且 PATH 指向 /usr/bin,迁移到 rustup 后请确认 PATH 包含 $HOME/.cargo/bin(执行 source $HOME/.cargo/env)
上述差异与迁移思路适用于在系统仓库与 rustup 之间做取舍。
常见问题与加速建议
- 1)命令未找到或仍是旧版本:新开终端或执行 source $HOME/.cargo/env;确认 PATH 中 $HOME/.cargo/bin 位于 /usr/bin 之前(which rustc 应指向 ~/.cargo/bin/rustc)
- 2)国内下载慢:可配置镜像加速
- Cargo 索引镜像(~/.cargo/config):
- [source.crates-io]
replace-with = ‘tuna’
- [source.tuna]
registry = “https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git”
- Rustup 工具链镜像(可选,写入 shell 配置如 ~/.bashrc):
- export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static
- 3)编译报错如“linker not found”:安装构建工具链 sudo apt install build-essential 或 clang,确保系统具备 C 链接器
以上可解决环境未生效、下载慢与链接器缺失等典型问题。