在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進行開發。