温馨提示×

Debian Rust库如何安装与管理

小樊
46
2026-01-03 15:09:53
栏目: 编程语言

Debian 上安装与管理 Rust 库

一 安装与工具链选择

  • 使用发行版仓库安装(稳定、系统级、便于集中更新)
    • 更新索引并安装工具链:sudo apt update && sudo apt install rustc cargo
    • 验证:rustc --versioncargo --version
    • 适合服务器/多用户环境,版本通常较旧但稳定。
  • 使用 rustup 安装(多版本管理、获取最新稳定版或 nightly)
    • 安装:curl --proto ‘=https’ --tlsv1.2 -sSf https://sh.rustup.rs | sh
    • 使环境生效:source “$HOME/.cargo/env”
    • 验证:rustc --versioncargo --version
    • 适合开发者,便于切换工具链与更新。

二 项目内安装与管理库(推荐)

  • 创建项目并添加依赖
    • 新建:cargo new mylib && cd mylib
    • Cargo.toml[dependencies] 中声明库与版本,例如:
      • rand = “0.8”
  • 获取与构建
    • 下载并编译依赖:cargo build
    • 运行测试:cargo test
    • 运行示例:cargo run
  • 升级依赖
    • 交互式升级:cargo update
    • 精确编辑 Cargo.toml 的版本号后再次构建以生效。

三 全局安装可执行工具(可选)

  • 安装到用户本地二进制目录:cargo install ripgrep
  • $HOME/.cargo/bin 加入 PATH,以便直接运行已安装的可执行文件。

四 加速与镜像配置

  • rustup 镜像(工具链下载)
    • 设置环境变量(示例为中科大镜像):
      • export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static
      • export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup
  • crates.io 索引镜像(依赖下载)
    • ~/.cargo/config.toml 中添加:
      • [source.crates-io]
      • replace-with = ‘rsproxy’
      • [source.rsproxy]
      • registry = “https://rsproxy.cn/crates.io-index”
      • [registries.rsproxy]
      • index = “https://rsproxy.cn/crates.io-index”
      • [net]
      • git-fetch-with-cli = true
  • 说明:镜像仅加速下载,不会改变依赖解析结果。

五 卸载与维护

  • 卸载 rustup 管理的工具链
    • 交互式移除:rustup self uninstall
  • 卸载发行版包管理器安装的 Rust
    • 移除包:sudo apt remove cargo(或 sudo apt remove rustc
    • 清理无用依赖:sudo apt autoremove
  • 常规维护
    • rustup 更新工具链:rustup update
    • 查看/切换工具链:rustup showrustup default stable
    • 构建与清理产物:cargo cleancargo build --release

0