首先确保系统包列表是最新的,避免后续安装依赖冲突:
sudo apt update
Rust编译及项目构建需要build-essential(包含gcc、make等工具)、curl(下载rustup)等依赖:
sudo apt install curl build-essential gcc make -y
Rust官方推荐通过rustup管理Rust版本及工具链(如stable、beta、nightly)。执行以下命令安装:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
安装过程中会提示选择工具链类型,**默认选择default(稳定版)**即可。安装完成后,rustup会自动配置环境变量,但需重新加载shell使配置生效:
source $HOME/.cargo/env
通过以下命令检查Rust编译器(rustc)和包管理器(cargo)是否安装成功:
rustc --version # 查看Rust编译器版本
cargo --version # 查看Cargo版本
若显示版本信息(如rustc 1.75.0),则说明安装成功。
为加快crates.io(Rust包仓库)的下载速度,可配置国内镜像(如清华、中科大源)。以清华源为例:
mkdir -p ~/.cargo
cat <<EOF > ~/.cargo/config.toml
[source.crates-io]
replace-with = 'tuna'
[source.tuna]
registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"
EOF
配置完成后,后续cargo操作(如cargo build)将自动使用国内镜像。
使用cargo快速创建新项目:
cargo new hello_world # 创建名为hello_world的项目(自动生成src/main.rs)
cd hello_world # 进入项目目录
项目结构如下:
hello_world/
├── Cargo.toml # 项目配置文件(依赖、元数据等)
└── src/
└── main.rs # 主程序入口(默认输出"Hello, world!")
编译并运行项目:
cargo build # 编译项目(生成target/debug/hello_world)
cargo run # 编译并运行(直接输出"Hello, world!")
rustfmt(官方格式化工具)rustup component add rustfmt
使用:cargo fmt(格式化当前项目代码)。clippy(官方linter,提示潜在错误)rustup component add clippy
使用:cargo clippy(检查代码质量问题)。cargo-deb(将Rust项目打包为.deb格式)cargo install cargo-deb
使用:cargo deb(在target/debian目录生成.deb文件,可通过dpkg -i安装)。若使用VS Code,可安装以下插件提升Rust开发效率:
Cargo.toml文件的编辑体验。通过以上步骤,即可在Debian系统中完成Rust环境的搭建与基础开发。后续可根据项目需求,通过cargo管理依赖(如添加serde用于JSON解析)、运行测试(cargo test)或发布到crates.io(cargo publish)。