外部 crate 导入
什么是外部 crate
外部 crate 是你的项目依赖的第三方库或者标准库之外的包。Rust 通过 Cargo 管理外部依赖:在 Cargo.toml 的 [dependencies] 中声明依赖,然后在代码中用 use 导入使用。Rust 的包生态系统托管在 crates.io 上。
# Cargo.toml
[dependencies]
serde = "1.0"
serde_json = "1.0"
rand = "0.8"// 在代码中导入外部 crate 的项
use serde::{Serialize, Deserialize};
use rand::Rng;
#[derive(Serialize, Deserialize, Debug)]
struct User {
name: String,
age: u32,
}
fn main() {
let user = User { name: String::from("张三"), age: 28 };
// 使用 serde_json
let json = serde_json::to_string(&user).unwrap();
println!("JSON: {}", json);
// 使用 rand
let mut rng = rand::thread_rng();
let n: u32 = rng.gen_range(1..=100);
println!("随机数: {}", n);
}添加依赖的方式
在 Cargo.toml 中手动添加
[dependencies]
# 最简写法:只指定版本
serde = "1.0"
# 带 features 的写法
serde = { version = "1.0", features = ["derive"] }
# 指定 Git 仓库
# my_lib = { git = "https://github.com/user/repo.git", branch = "main" }
# 指定本地路径
# my_lib = { path = "../my_lib" }
# 可选依赖
# some_lib = { version = "1.0", optional = true }用 cargo add 命令
# 添加最新版本
cargo add serde
# 添加指定版本
cargo add serde@1.0
# 添加并启用 features
cargo add serde --features derive
# 添加为开发依赖
cargo add mockall --dev标准库 vs 外部 crate
标准库(std)是 Rust 内置的,不需要在 Cargo.toml 中声明就可以直接使用。
// 标准库:直接用,不需要声明依赖
use std::collections::HashMap;
use std::fs;
use std::io::{self, Read};
// 外部 crate:需要先在 Cargo.toml 声明
// use serde::Serialize;
// use tokio::runtime::Runtime;
fn main() {
// 标准库使用示例
let mut map = HashMap::new();
map.insert("rust", 2015);
map.insert("go", 2009);
for (lang, year) in &map {
println!("{} 发布于 {}年", lang, year);
}
}| 类别 | 需要 Cargo.toml 声明? | 导入方式 | 示例 |
|---|---|---|---|
标准库 std | 不需要 | use std::... | use std::collections::HashMap |
核心库 core | 不需要 | use core::... | use core::fmt::Display |
分配库 alloc | 不需要 | use alloc::... | use alloc::vec::Vec |
| 外部 crate | 需要 | use crate_name::... | use serde::Serialize |
版本号语义
Cargo 使用语义化版本(SemVer)来管理依赖版本。
[dependencies]
# "1.0" 等价于 "^1.0",表示 >=1.0.0 且 <2.0.0
serde = "1.0"
# 精确版本
serde = "=1.0.193"
# 范围指定
# serde = ">=1.0, <1.5"
# 波浪号:只允许补丁版本更新
# serde = "~1.0.100" # >=1.0.100 且 <1.1.0
# 星号通配
# serde = "1.*" # >=1.0.0 且 <2.0.0| 写法 | 含义 | 示例范围 |
|---|---|---|
"1.0" / "^1.0" | 兼容更新 | >=1.0.0, <2.0.0 |
"=1.0.5" | 精确版本 | 只用 1.0.5 |
"~1.0.5" | 补丁更新 | >=1.0.5, <1.1.0 |
"1.*" | 主版本内任意 | >=1.0.0, <2.0.0 |
">=1.0, <1.5" | 自定义范围 | >=1.0.0, <1.5.0 |
Features 特性开关
很多 crate 提供可选功能,用 features 来控制。
[dependencies]
# 启用 derive 特性(让 serde 提供 #[derive(Serialize, Deserialize)])
serde = { version = "1.0", features = ["derive"] }
# 启用多个特性
# tokio = { version = "1.0", features = ["full"] }
# 默认不启用任何特性
# some_lib = { version = "1.0", default-features = false }
# 不启用默认特性,只启用指定的
# some_lib = { version = "1.0", default-features = false, features = ["std", "alloc"] }在代码中使用外部 crate
// 2018 Edition 之后,外部 crate 直接用名字作为路径根
// 不需要像 2015 Edition 那样写 extern crate xxx;
use std::collections::HashMap;
// 假设已在 Cargo.toml 中添加了依赖
// 下面展示常见的导入模式
// 模式一:导入具体类型
// use serde::{Serialize, Deserialize};
// 模式二:导入模块
// use serde_json; // 之后用 serde_json::to_string()
// 模式三:嵌套导入
// use tokio::{self, runtime::Runtime, sync::Mutex};
// 模式四:重命名
// use serde_json::Value as JsonValue;
fn main() {
let mut scores = HashMap::new();
scores.insert("数学", 95);
scores.insert("语文", 88);
scores.insert("英语", 92);
for (subject, score) in &scores {
println!("{}: {} 分", subject, score);
}
}开发依赖和构建依赖
# 正常依赖:编译和运行时都需要
[dependencies]
serde = "1.0"
# 开发依赖:只在测试和示例中使用
[dev-dependencies]
# mockall = "0.12"
# criterion = "0.5"
# 构建依赖:只在 build.rs 中使用
[build-dependencies]
# cc = "1.0"基本示例
展示一个使用标准库多个模块的完整程序:
use std::collections::HashMap;
use std::fmt;
// 自定义结构体
struct StudentReport {
name: String,
scores: HashMap<String, f64>,
}
impl StudentReport {
fn new(name: &str) -> Self {
StudentReport {
name: name.to_string(),
scores: HashMap::new(),
}
}
fn add_score(&mut self, subject: &str, score: f64) {
self.scores.insert(subject.to_string(), score);
}
fn average(&self) -> f64 {
if self.scores.is_empty() {
return 0.0;
}
let sum: f64 = self.scores.values().sum();
sum / self.scores.len() as f64
}
fn highest(&self) -> Option<(&str, f64)> {
self.scores.iter()
.max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
.map(|(k, &v)| (k.as_str(), v))
}
fn lowest(&self) -> Option<(&str, f64)> {
self.scores.iter()
.min_by(|a, b| a.1.partial_cmp(b.1).unwrap())
.map(|(k, &v)| (k.as_str(), v))
}
}
// 实现 Display trait(来自 std::fmt)
impl fmt::Display for StudentReport {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "=== {} 的成绩单 ===", self.name)?;
// 按科目名排序输出
let mut subjects: Vec<_> = self.scores.iter().collect();
subjects.sort_by_key(|(k, _)| k.clone());
for (subject, score) in &subjects {
writeln!(f, " {}: {:.1}", subject, score)?;
}
writeln!(f, " ---")?;
writeln!(f, " 平均分: {:.1}", self.average())?;
if let Some((subj, score)) = self.highest() {
writeln!(f, " 最高: {} ({:.1})", subj, score)?;
}
if let Some((subj, score)) = self.lowest() {
writeln!(f, " 最低: {} ({:.1})", subj, score)?;
}
Ok(())
}
}
fn main() {
let mut report = StudentReport::new("张三");
report.add_score("数学", 95.5);
report.add_score("语文", 88.0);
report.add_score("英语", 92.0);
report.add_score("物理", 85.5);
report.add_score("化学", 91.0);
println!("{}", report);
}常见问题
问题一:2015 Edition 的 extern crate 还需要写吗?
2018 Edition 之后不需要了。编译器会根据 Cargo.toml 中的依赖自动把外部 crate 引入作用域。extern crate 只在极少数场景下还需要(比如 extern crate alloc 在 no_std 环境中)。
问题二:Cargo.lock 是什么?
Cargo.lock 记录了所有依赖的精确版本号,确保团队成员和 CI 构建使用完全相同的版本。二进制项目应该提交 Cargo.lock,库项目一般不提交。
问题三:怎么更新依赖版本?
# 在 SemVer 兼容范围内更新
cargo update
# 更新指定的包
cargo update -p serde
# 查看过时的依赖
cargo outdated # 需要安装 cargo-outdated问题四:依赖冲突怎么办?
如果两个依赖需要同一个 crate 的不同版本,Cargo 会尝试自动解决。如果无法兼容,需要手动调整版本约束,或者等上游更新依赖。
适用场景
- 添加第三方功能:序列化(serde)、HTTP(reqwest)、异步(tokio)等
- 标准库扩展:标准库不够用时引入社区 crate
- 工具库:日志(tracing)、CLI(clap)、错误处理(anyhow)等
- 开发工具:测试框架、性能测试、mock 库
注意事项
- 2018 Edition 之后不需要
extern crate声明 - 外部依赖必须在
Cargo.toml的[dependencies]中声明 - 标准库不需要声明,直接
use std::...使用 - 注意版本号语义:
"1.0"表示^1.0(兼容更新) - 启用 features 时注意是否需要关闭 default-features
- 二进制项目应该提交
Cargo.lock - 定期用
cargo update更新依赖的补丁版本 - 谨慎添加依赖,每个依赖都增加编译时间和维护负担
总结
外部 crate 导入是 Rust 项目使用第三方库的标准方式。在 Cargo.toml 的 [dependencies] 中声明依赖名和版本号,在代码中用 use crate_name::item 导入使用。Cargo 使用语义化版本管理依赖,通过 features 控制可选功能。2018 Edition 之后不再需要 extern crate 声明。标准库内置可用,不需要额外声明。合理管理依赖——只添加必要的 crate,定期更新版本,注意版本兼容性——是维护健康 Rust 项目的重要实践。