在Debian系统中,Rust库的安装与管理主要依赖 Cargo(Rust官方包管理器)和rustup(Rust官方工具链管理器)。以下是详细步骤:
要管理Rust库,需先安装Rust编译器(rustc)和包管理器(cargo)。推荐使用rustup(官方工具链管理器),因为它能灵活管理多个Rust版本和工具链。
# 更新系统包列表
sudo apt update
# 安装curl(rustup需要)
sudo apt install -y curl
# 下载并运行rustup安装脚本
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# 按照提示完成安装(默认选项即可)
# 安装完成后,重新加载shell配置文件(如.bashrc或.zshrc)
source ~/.bashrc # 或 source ~/.zshrc
# 检查Rust编译器版本
rustc --version # 应输出类似"rustc 1.75.0 (x86_64-unknown-linux-gnu)"
# 检查Cargo版本
cargo --version # 应输出类似"cargo 1.75.0"
若不想使用rustup,可通过Debian官方仓库安装(版本可能滞后):
sudo apt update
sudo apt install -y rustc cargo
Cargo是Rust项目的核心工具,负责依赖管理、构建和发布。以下是常见操作:
# 创建名为"my_project"的新Rust项目
cargo new my_project
# 进入项目目录
cd my_project
项目结构会自动生成,包含Cargo.toml(依赖配置文件)和src/main.rs(主程序)。
Rust库(称为"crates")需通过Cargo.toml声明。有两种方式添加:
Cargo.toml:[dependencies]部分添加库名及版本(如添加rand库,版本0.8):[dependencies]
rand = "0.8"
cargo add命令(需安装cargo-edit插件):cargo install cargo-edit
再通过命令添加依赖:cargo add rand
# 下载并编译依赖,生成可执行文件
cargo build
# 编译并直接运行项目
cargo run
# 仅编译(不运行)
cargo build --release # 优化后的版本(用于生产)
# 更新所有依赖到Cargo.toml中指定的最新版本
cargo update
# 更新指定依赖(如rand)
cargo update -p rand
Cargo.toml:[dependencies]中对应的库名,然后运行:cargo build # 清理未使用的依赖
cargo remove命令(需cargo-edit):cargo remove rand
若需要安装多个Rust版本或切换版本,可使用rustup:
rustup toolchain list
rustup install 1.70.0 # 安装Rust 1.70.0
rustup default 1.70.0 # 将默认工具链切换到1.70.0
在项目根目录创建.rust-version文件,写入所需版本:
echo "1.70.0" > .rust-version
进入项目时,rustup会自动切换到指定版本。
rustup:它能确保安装最新版本的Rust,并灵活管理工具链,避免APT仓库版本滞后的问题。~/.cargo/registry中,清理缓存可使用cargo cache --clean(需安装cargo-cache插件)。~/.cargo/registry复制到目标机器。通过以上步骤,可在Debian系统中高效安装、管理和使用Rust库。