Linux系统如何配置Rust的开发工具链
小樊
44
2025-12-24 04:31:43
Linux 配置 Rust 开发工具链
一 安装与基础配置
- 安装系统构建依赖(Debian/Ubuntu 示例):sudo apt update && sudo apt install -y curl build-essential gcc make。这些依赖用于编译部分 Rust 包和原生依赖。
- 使用 rustup 安装工具链:运行命令:curl --proto ‘=https’ --tlsv1.2 -sSf https://sh.rustup.rs | sh,按提示完成安装。
- 使环境变量生效:执行 source $HOME/.cargo/env(大多数情况下安装器会自动写入 ~/.bashrc 或 ~/.zshrc;若未生效,可手动添加 export PATH=“$HOME/.cargo/bin:$PATH” 到相应配置文件并 source 使其生效)。
- 验证安装:rustc –version、cargo –version、rustup –version 均应输出版本信息。
二 国内网络加速
- 安装阶段临时使用镜像(任选其一或同时设置):
- 设置更新源与分发源:export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup;export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup。
- 然后再次执行安装脚本。
- 持久化镜像(可选):将上面两行写入 ~/.bashrc 或 ~/.zshrc 以长期生效。
- Cargo 包索引镜像(crates.io):在 $HOME/.cargo/config 中添加:
[source.crates-io]
registry = “https://github.com/rust-lang/crates.io-index”
replace-with = ‘ustc’
[source.ustc]
registry = “git://mirrors.ustc.edu.cn/crates.io-index”
三 工具链管理与常用命令
- 查看与更新:rustup update 更新工具链;rustup show 查看当前工具链与项目覆盖。
- 安装与切换版本:rustup install ;rustup default ;临时使用:RUSTUP_TOOLCHAIN=nightly cargo build。
- 组件管理:rustup component list;rustup component add (如 rust-src、clippy、rustfmt 等)。
四 编辑器与调试配置
- Visual Studio Code:安装扩展 rust-analyzer;如需调试,安装 CodeLLDB 或 Native Debug。
- 创建并运行项目:cargo new hello && cd hello && cargo run,应输出 Hello, World!。
五 常见问题与排查
- 命令未找到:确认 ~/.cargo/bin 已加入 PATH,执行 source $HOME/.cargo/env 或重开终端。
- 安装或更新缓慢/失败:检查是否配置了 RUSTUP_DIST_SERVER / RUSTUP_UPDATE_ROOT 镜像;必要时设置超时与并发:export RUSTUP_DOWNLOAD_TIMEOUT=300;export RUSTUP_CONCURRENT_DOWNLOADS=4。
- 需要 C/C++ 工具链:Rust 的构建与部分原生依赖需要 gcc/clang 与构建工具,确保已安装(见第一步)。
- 卸载:rustup self uninstall。