首先确保系统包列表是最新的,避免后续安装依赖冲突:
sudo apt update && sudo apt upgrade -y
Rust编译及工具链需要curl、build-essential(包含gcc、make等)等工具,安装命令如下:
sudo apt install curl build-essential -y
rustup是Rust官方推荐的工具链管理工具,支持安装、更新和管理多个Rust版本。运行以下命令安装:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --no-modify-path -y
注:
--no-modify-path选项将Rust安装到/opt/rust目录(避免修改系统PATH),若需全局使用,可省略此选项。
安装完成后,需将Rust工具链路径添加到环境变量中,实现全局可用:
echo 'export RUSTUP_HOME=/opt/rust' | sudo tee -a /etc/profile.d/rust.sh
echo 'export PATH=$PATH:/opt/rust/bin' | sudo tee -a /etc/profile.d/rust.sh
source /etc/profile # 立即生效
若未使用
--no-modify-path,可跳过此步(rustup会自动配置)。
通过以下命令检查Rust编译器(rustc)和包管理器(cargo)是否安装成功:
rustc --version # 应显示Rust编译器版本(如rustc 1.75.0)
cargo --version # 应显示Cargo版本(如cargo 1.75.0)
中国大陆用户可使用清华或中科大镜像源加速crates.io依赖下载,编辑~/.cargo/config文件(不存在则创建):
mkdir -p ~/.cargo
cat <<EOF > ~/.cargo/config
[source.crates-io]
replace-with = 'tuna' # 或 'ustc'(中科大镜像)
[source.tuna]
registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"
[source.ustc]
registry = "https://mirrors.ustc.edu.cn/crates.io-index"
EOF
使用Cargo快速创建项目:
cargo new hello_world # 创建名为hello_world的项目目录
cd hello_world # 进入项目目录
cargo run # 编译并运行项目(输出"Hello, world!")
rustfmt(Rust官方格式化工具):rustup component add rustfmt
clippy(Rust lint工具,用于捕获潜在错误):rustup component add clippy
推荐使用VS Code或IntelliJ IDEA搭配Rust插件:
~/.cargo/bin)。通过以上步骤,即可在Debian系统上完成Rust开发环境的配置,满足日常开发需求。若需切换Rust版本,可使用rustup install <version>安装指定版本,再用rustup default <version>设置为默认版本。