依赖管理与 crates.io
学习目标
- 掌握依赖声明方式
- 理解语义化版本
- 学会查找和选择 crate
核心概念
版本声明
[dependencies]
serde = "1.0" # ^1.0(兼容 1.x)
serde_json = ">=1.0,<2.0" # 范围
tokio = "~1.20" # >=1.20.0, <1.21.0
rand = "=0.8.5" # 精确版本
语义化版本(SemVer)
主版本.次版本.补丁
↑ ↑ ↑
不兼容 新功能 Bug修复
^1.2.3 → >=1.2.3, <2.0.0
~1.2.3 → >=1.2.3, <1.3.0
Git 依赖
[dependencies]
my_lib = { git = "https://github.com/user/repo", branch = "main" }
my_lib = { git = "https://github.com/user/repo", tag = "v1.0" }
本地依赖
[dependencies]
my_lib = { path = "../my_lib" }
Feature 条件编译
# 库的 Cargo.toml
[features]
default = ["json"]
json = ["serde", "serde_json"]
full = ["json", "xml", "yaml"]
[dependencies]
serde = { version = "1", optional = true }
serde_json = { version = "1", optional = true }
# 使用方的 Cargo.toml
[dependencies]
my_lib = { version = "1", features = ["full"] }
// 代码中条件编译
#[cfg(feature = "json")]
pub fn parse_json(input: &str) -> serde_json::Value {
serde_json::from_str(input).unwrap()
}
常用命令
cargo add serde --features derive # 添加依赖
cargo remove serde # 移除依赖
cargo update # 更新依赖
cargo tree # 查看依赖树
cargo tree -d # 查看重复依赖
实践练习
练习 1:添加 HTTP 客户端
# Cargo.toml
[dependencies]
reqwest = { version = "0.12", features = ["json"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
use serde::Deserialize;
#[derive(Deserialize, Debug)]
struct User {
name: String,
email: String,
}
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
let user: User = reqwest::get("https://api.example.com/user")
.await?
.json()
.await?;
println!("{:?}", user);
Ok(())
}
小结
| 语法 | 含义 |
|---|---|
"1.0" | ^1.0,兼容更新 |
"~1.2" | 补丁更新 |
"=1.2.3" | 精确版本 |
features | 启用可选功能 |
optional = true | 可选依赖 |
练习编辑器
rust
Loading...