在 Ubuntu 上使用 Cargo 管理 Rust 项目
一 安装与准备
sudo apt update && sudo apt install -y curl build-essential gcc make
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"
验证安装:rustc --version
cargo --version
若在国内下载缓慢,可设置镜像后再执行安装脚本:export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static
export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup
备选方案(系统级安装,版本可能较旧):sudo apt install -y rustc cargo
以上步骤完成后即可在用户环境使用最新工具链与 Cargo。二 配置 Cargo 与镜像
[registries]
crates-io = { index = "https://mirrors.tuna.tsinghua.edu.cn/crates.io-index" }
保存后 Cargo 将优先从镜像拉取依赖索引。三 常用 Cargo 命令
cargo new hello_world
cd hello_world
cargo build # 构建(默认 debug)
cargo run # 构建并运行
cargo check # 快速检查是否能编译通过(不生成可执行文件)
cargo test # 运行测试
[dependencies]
rand = "0.8"
保存后执行 cargo build 自动下载并编译依赖。四 多版本工具链与更新
rustup update # 更新所有已安装工具链与组件
rustup toolchain list # 查看已安装工具链
rustup default stable # 设置默认工具链
rustup override set nightly # 为当前项目覆盖为 nightly
建议始终通过 rustup 更新,保持工具链与 Cargo 一致。五 常见问题与卸载
sudo apt install -y build-essential
rustup self uninstall
sudo apt remove -y rustc cargo
sudo apt autoremove -y
cargo 可能不可用;执行 source "$HOME/.cargo/env" 或重启终端即可生效。