Rust在Ubuntu上如何使用Cargo包管理器
导读:在 Ubuntu 上使用 Cargo 管理 Rust 项目 一 安装与准备 推荐通过官方工具链管理器 rustup 安装,获取最新稳定版并同时安装 Cargo。先安装基础编译工具,再下载并运行安装脚本,最后加载环境变量:sudo apt...
在 Ubuntu 上使用 Cargo 管理 Rust 项目
一 安装与准备
- 推荐通过官方工具链管理器 rustup 安装,获取最新稳定版并同时安装 Cargo。先安装基础编译工具,再下载并运行安装脚本,最后加载环境变量:
验证安装: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
以上步骤完成后即可在用户环境使用最新工具链与 Cargo。sudo apt install -y rustc cargo
二 配置 Cargo 与镜像
- 配置 crates.io 索引镜像(可选,提升依赖下载速度)。编辑或创建文件 ~/.cargo/config.toml,加入:
保存后 Cargo 将优先从镜像拉取依赖索引。[registries] crates-io = { index = "https://mirrors.tuna.tsinghua.edu.cn/crates.io-index" }
三 常用 Cargo 命令
- 创建项目:
cargo new hello_world cd hello_world - 构建与运行:
cargo build # 构建(默认 debug) cargo run # 构建并运行 cargo check # 快速检查是否能编译通过(不生成可执行文件) cargo test # 运行测试 - 依赖管理:在 Cargo.toml 的 [dependencies] 下添加,例如:
保存后执行[dependencies] rand = "0.8"cargo build自动下载并编译依赖。
四 多版本工具链与更新
- 使用 rustup 管理多个工具链(如 stable/beta/nightly)与组件:
建议始终通过rustup update # 更新所有已安装工具链与组件 rustup toolchain list # 查看已安装工具链 rustup default stable # 设置默认工具链 rustup override set nightly # 为当前项目覆盖为 nightlyrustup更新,保持工具链与 Cargo 一致。
五 常见问题与卸载
- 编译报错 linker ‘cc’ not found:安装编译工具链
sudo apt install -y build-essential - 卸载:
- 若通过 rustup 安装:
rustup self uninstall - 若通过 apt 安装:
sudo apt remove -y rustc cargo sudo apt autoremove -y
- 若通过 rustup 安装:
- 小提示:确保 ~/.cargo/bin 已加入 PATH,否则
cargo可能不可用;执行source "$HOME/.cargo/env"或重启终端即可生效。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Rust在Ubuntu上如何使用Cargo包管理器
本文地址: https://pptw.com/jishu/766636.html
