在Linux上,Rust的官方包管理器是Cargo。Cargo不仅负责项目的构建和依赖管理,还提供了许多其他有用的功能,如测试、文档生成和发布等。以下是如何在Linux上使用Cargo的基本步骤:
通过Rust官网安装: 访问Rust官网,下载并运行安装脚本。
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
按照提示完成安装。
通过包管理器安装:
sudo apt update
sudo apt install rustc cargo
sudo dnf install rust cargo
sudo pacman -S rust cargo
创建一个新的Rust项目:
cargo new my_project
cd my_project
进入项目目录后,你可以看到一个基本的项目结构,包括src/main.rs
(主程序入口)和Cargo.toml
(项目的配置文件)。
编译项目:
cargo build
这会在target/debug
目录下生成可执行文件。
优化编译(发布模式):
cargo build --release
这会在target/release
目录下生成优化后的可执行文件。
运行调试版本:
cargo run
运行发布版本:
cargo run --release
添加依赖:
编辑Cargo.toml
文件,添加所需的依赖项,例如:
[dependencies]
rand = "0.8"
更新依赖:
cargo update
查看依赖树:
cargo tree
测试项目:
cargo test
生成文档:
cargo doc --open
清理构建缓存:
cargo clean
通过这些基本步骤,你可以在Linux上轻松地使用Rust和Cargo进行开发。