Rust项目的运行依赖Rust编译器(rustc)和包管理工具(cargo)。推荐通过rustup(Rust官方安装工具)安装,确保版本最新:
sudo apt updatecurl(若未安装):sudo apt install curlrustup安装脚本:curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shsource $HOME/.cargo/envrustc --version(显示版本号即成功)。可选择新建项目或使用现有项目:
cargo new 项目名称(如cargo new hello_rust),会生成包含src/main.rs(主程序)和Cargo.toml(配置文件)的标准项目结构。cd 项目名称(如cd hello_rust)。用文本编辑器(如nano、vscode)打开src/main.rs,编写Rust代码。例如,最简单的“Hello World”程序:
fn main() {
println!("Hello, Debian!"); // 输出自定义信息
}
保存文件后返回终端。
cargo run,Cargo会自动编译并执行项目。输出示例:Compiling hello_rust v0.1.0 (/path/to/hello_rust)
Finished dev [unoptimized + debuginfo] target(s) in 0.50s
Running `target/debug/hello_rust`
Hello, Debian!
cargo build --release,生成的可执行文件位于target/release/项目名称(如target/release/hello_rust),运行:./target/release/hello_rust
发布版本会移除调试信息,提升运行速度。Rust项目的依赖在Cargo.toml中声明,Cargo会自动下载并管理。例如,添加serde(JSON序列化库):
Cargo.toml,在[dependencies]部分添加:[dependencies]
serde = "1.0" # 指定版本
cargo build,Cargo会自动下载serde及其依赖到本地缓存(~/.cargo/registry)。若需让Rust项目作为系统服务后台运行(如Web服务),可创建systemd服务文件:
sudo nano /etc/systemd/system/your_project.service[Unit]
Description=Your Rust Project
After=network.target
[Service]
User=your_username # 替换为实际用户
Group=your_group # 替换为实际用户组
ExecStart=/path/to/your_project/target/release/your_executable # 可执行文件路径
Restart=always # 崩溃后自动重启
[Install]
WantedBy=multi-user.target
sudo systemctl enable your_project # 开机自启
sudo systemctl start your_project # 立即启动
sudo systemctl status your_project。~/.cargo/config.toml中添加:[source.crates-io]
replace-with = 'ustc'
[source.ustc]
registry = "https://mirrors.ustc.edu.cn/crates.io-index"
chmod +x target/release/your_executable。通过以上步骤,即可在Debian系统上顺利运行、管理和部署Rust项目。