温馨提示×

Rust在Ubuntu上如何使用Cargo包管理器

小樊
44
2025-12-08 15:19:46
栏目: 编程语言

在 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
    
    备选方案(系统级安装,版本可能较旧):
    sudo apt install -y rustc cargo
    
    以上步骤完成后即可在用户环境使用最新工具链与 Cargo。

二 配置 Cargo 与镜像

  • 配置 crates.io 索引镜像(可选,提升依赖下载速度)。编辑或创建文件 ~/.cargo/config.toml,加入:
    [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     # 运行测试
    
  • 依赖管理:在 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   # 为当前项目覆盖为 nightly
    
    建议始终通过 rustup 更新,保持工具链与 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
      
  • 小提示:确保 ~/.cargo/bin 已加入 PATH,否则 cargo 可能不可用;执行 source "$HOME/.cargo/env" 或重启终端即可生效。

0