debian

如何在Debian中使用Rust进行开发

小樊
42
2025-10-23 11:38:00
栏目: 编程语言

在Debian中使用Rust进行开发的完整步骤

1. 更新系统包列表

首先确保系统包列表是最新的,避免后续安装依赖冲突:

sudo apt update

2. 安装必要依赖包

Rust编译及项目构建需要build-essential(包含gcc、make等工具)、curl(下载rustup)等依赖:

sudo apt install curl build-essential gcc make -y

3. 安装Rust工具链(推荐使用rustup)

Rust官方推荐通过rustup管理Rust版本及工具链(如stable、beta、nightly)。执行以下命令安装:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

安装过程中会提示选择工具链类型,**默认选择default(稳定版)**即可。安装完成后,rustup会自动配置环境变量,但需重新加载shell使配置生效:

source $HOME/.cargo/env

4. 验证Rust安装

通过以下命令检查Rust编译器(rustc)和包管理器(cargo)是否安装成功:

rustc --version  # 查看Rust编译器版本
cargo --version  # 查看Cargo版本

若显示版本信息(如rustc 1.75.0),则说明安装成功。

5. (可选)配置国内镜像源

为加快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)将自动使用国内镜像。

6. 创建并运行第一个Rust项目

使用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!")

7. 安装常用开发工具(可选)

8. (可选)使用VS Code增强开发体验

若使用VS Code,可安装以下插件提升Rust开发效率:

通过以上步骤,即可在Debian系统中完成Rust环境的搭建与基础开发。后续可根据项目需求,通过cargo管理依赖(如添加serde用于JSON解析)、运行测试(cargo test)或发布到crates.iocargo publish)。

0
看了该问题的人还看了