24.1 常用 Crate 推荐24.1.1 Web 开发[dependencies] # Web 框架 axum 0.7 # 现代、高性能的 Web 框架 actix-web 4.4 # 成熟的 Web 框架 rocket 0.5 # 易用的 Web 框架 # HTTP 客户端 reqwest 0.11 # 高级 HTTP 客户端 hyper 1.0 # 底层 HTTP 库 # 序列化 serde { version 1.0, features [derive] } serde_json 1.0 # JSON 支持 toml 0.8 # TOML 支持 # 模板引擎 askama 0.12 # 编译时模板 tera 1.19 # 运行时模板24.1.2 异步运行时[dependencies] # 异步运行时 tokio { version 1.35, features [full] } async-std 1.12 # 异步工具 futures 0.3 async-trait 0.124.1.3 数据库[dependencies] # ORM diesel { version 2.1, features [postgres] } sea-orm 0.12 # 异步数据库驱动 sqlx { version 0.7, features [runtime-tokio, postgres] } tokio-postgres 0.7 # Redis redis { version 0.24, features [tokio-comp] }24.1.4 CLI 工具[dependencies] # 命令行解析 clap { version 4.4, features [derive] } structopt 0.3 # 终端 UI crossterm 0.27 ratatui 0.25 # 进度条 indicatif 0.17 # 颜色输出 colored 2.124.1.5 错误处理[dependencies] anyhow 1.0 # 应用级错误处理 thiserror 1.0 # 库级错误处理 eyre 0.6 # 增强的错误报告24.1.6 日志与追踪[dependencies] # 日志 log 0.4 env_logger 0.11 # 追踪 tracing 0.1 tracing-subscriber 0.324.1.7 测试[dev-dependencies] # 测试框架 proptest 1.4 # 属性测试 quickcheck 1.0 # 快速检查 mockall 0.12 # Mock 框架 # 基准测试 criterion 0.524.1.8 实用工具[dependencies] # 时间处理 chrono 0.4 time 0.3 # 随机数 rand 0.8 # 正则表达式 regex 1.10 # 迭代器工具 itertools 0.12 # 并行处理 rayon 1.824.2 评估 Crate 质量24.2.1 检查清单在 crates.io 上检查下载量高下载量通常意味着广泛使用最近更新活跃维护的项目更可靠版本号1.0 版本通常更稳定文档完善的文档是质量的标志许可证确保许可证符合项目需求在 GitHub 上检查Star 数量社区认可度Issue 响应维护者的活跃度PR 合并速度项目的健康度测试覆盖率代码质量CI/CD自动化测试24.2.2 使用 cargo-audit# 安装cargoinstallcargo-audit# 检查安全漏洞cargoaudit# 修复漏洞cargoaudit fix24.2.3 使用 cargo-outdated# 安装cargoinstallcargo-outdated# 检查过时的依赖cargooutdated# 显示详细信息cargooutdated-v24.2.4 使用 cargo-tree# 查看依赖树cargotree# 查看特定包的依赖cargotree-ptokio# 查看反向依赖cargotree-iserde24.3 版本管理24.3.1 语义化版本[dependencies] # 精确版本 serde 1.0.195 # 兼容版本默认 serde 1.0 # 1.0.0, 2.0.0 serde 1.0.195 # 1.0.195, 2.0.0 # 通配符 serde 1.* # 1.0.0, 2.0.0 # 范围 serde 1.0, 2.0 # 预发布版本 serde 1.0.0-alpha.124.3.2 Cargo.lock# 更新所有依赖到最新兼容版本cargoupdate# 更新特定依赖cargoupdate-pserde# 精确更新到指定版本cargoupdate-pserde--precise1.0.19524.3.3 工作空间版本管理# Cargo.toml (workspace root) [workspace] members [crate1, crate2] [workspace.dependencies] serde { version 1.0, features [derive] } tokio { version 1.35, features [full] } # crate1/Cargo.toml [dependencies] serde { workspace true } tokio { workspace true }24.4 依赖更新策略24.4.1 定期更新# 每周或每月运行cargooutdatedcargoupdatecargotest24.4.2 自动化更新Dependabot.github/dependabot.ymlversion:2updates:-package-ecosystem:cargodirectory:/schedule:interval:weeklyopen-pull-requests-limit:10reviewers:-your-username24.4.3 渐进式更新// 使用 feature flags 逐步迁移#[cfg(feature new-version)]usenew_crate::NewApi;#[cfg(not(feature new-version))]useold_crate::OldApi;fnmain(){#[cfg(feature new-version)]{println!(使用新版本);}#[cfg(not(feature new-version))]{println!(使用旧版本);}}24.5 构建自己的 Crate24.5.1 创建库 Crate# 创建库项目cargonew--libmy_cratecdmy_cratesrc/lib.rs//! # My Crate//!//! my_crate 是一个示例库展示如何创建 Rust crate。/// 将两个数字相加////// # Examples////// /// use my_crate::add;////// assert_eq!(add(2, 3), 5);/// pubfnadd(a:i32,b:i32)-i32{ab}#[cfg(test)]modtests{usesuper::*;#[test]fntest_add(){assert_eq!(add(2,3),5);}}24.5.2 配置 Cargo.toml[package] name my_crate version 0.1.0 edition 2021 authors [Your Name youexample.com] description A short description of my crate license MIT OR Apache-2.0 repository https://github.com/yourusername/my_crate documentation https://docs.rs/my_crate homepage https://github.com/yourusername/my_crate keywords [example, demo] categories [development-tools] readme README.md [dependencies] [dev-dependencies]24.5.3 编写文档//! # My Crate//!//! 这是 crate 级别的文档。/// 一个示例结构体////// # Examples////// /// use my_crate::MyStruct;////// let s MyStruct::new(42);/// assert_eq!(s.value(), 42);/// pubstructMyStruct{value:i32,}implMyStruct{/// 创建新实例pubfnnew(value:i32)-Self{MyStruct{value}}/// 获取值pubfnvalue(self)-i32{self.value}}生成文档# 生成并打开文档cargodoc--open# 测试文档中的示例cargotest--doc24.5.4 添加示例examples/basic.rsusemy_crate::add;fnmain(){letresultadd(2,3);println!(2 3 {},result);}运行示例cargorun--examplebasic24.6 发布 Crate24.6.1 准备发布# 1. 登录 crates.iocargologinyour-api-token# 2. 检查包cargopackage--list# 3. 本地测试cargopackagecargoinstall--path.# 4. 发布cargopublish# 5. 发布到特定 registrycargopublish--registrymy-registry24.6.2 版本发布流程# 1. 更新版本号# 编辑 Cargo.toml: version 0.2.0# 2. 更新 CHANGELOG.md# 记录变更# 3. 提交更改gitadd.gitcommit-mRelease v0.2.0# 4. 打标签gittag v0.2.0# 5. 推送gitpush origin main--tags# 6. 发布到 crates.iocargopublish24.6.3 撤回版本# 撤回版本不删除但标记为不推荐cargoyank--vers0.1.0# 取消撤回cargoyank--vers0.1.0--undo24.7 私有 Registry24.7.1 配置私有 Registry.cargo/config.toml[registries.my-registry] index https://my-registry.example.com/git/index [source.my-registry] registry https://my-registry.example.com/git/index24.7.2 使用私有依赖[dependencies] my-private-crate { version 0.1, registry my-registry }24.7.3 发布到私有 Registrycargopublish--registrymy-registry24.8 Feature Flags24.8.1 定义 Features[features] default [std] std [] async [tokio] full [std, async] [dependencies] tokio { version 1.35, optional true }24.8.2 使用 Features#[cfg(feature std)]usestd::collections::HashMap;#[cfg(not(feature std))]usealloc::collections::BTreeMap;#[cfg(feature async)]pubasyncfnasync_function(){println!(异步功能);}fnmain(){#[cfg(feature std)]println!(使用标准库);#[cfg(feature async)]{// 异步代码}}24.8.3 编译时选择 Features# 使用默认 featurescargobuild# 禁用默认 featurescargobuild --no-default-features# 启用特定 featurescargobuild--featuresasync# 启用多个 featurescargobuild--featuresstd,async常见误区与陷阱误区 1过度依赖# ❌ 不好依赖过多 [dependencies] crate1 1.0 crate2 1.0 crate3 1.0 # ... 50 个依赖 # ✅ 好只依赖必要的 [dependencies] serde 1.0 tokio 1.35误区 2不固定版本# ❌ 不好使用 * 通配符 [dependencies] serde * # ✅ 好指定版本范围 [dependencies] serde 1.0误区 3忽略安全更新# ❌ 不好从不更新依赖# ✅ 好定期检查和更新cargoauditcargooutdatedcargoupdate实战练习练习 24.1评估 Crate选择一个 crate 并评估其质量。参考答案# 1. 在 crates.io 上查看# - 下载量# - 版本号# - 文档链接# 2. 在 GitHub 上查看# - Star 数量# - Issue 数量# - 最近提交# 3. 检查依赖cargotree-pcrate-name# 4. 检查安全性cargoaudit# 5. 查看文档cargodoc--open练习 24.2创建并发布 Crate创建一个简单的工具库并发布到 crates.io。参考答案// src/lib.rs//! # String Utils//!//! 字符串处理工具库/// 反转字符串////// # Examples////// /// use string_utils::reverse;////// assert_eq!(reverse(hello), olleh);/// pubfnreverse(s:str)-String{s.chars().rev().collect()}/// 统计单词数pubfnword_count(s:str)-usize{s.split_whitespace().count()}#[cfg(test)]modtests{usesuper::*;#[test]fntest_reverse(){assert_eq!(reverse(hello),olleh);}#[test]fntest_word_count(){assert_eq!(word_count(hello world),2);}}# Cargo.toml [package] name string_utils version 0.1.0 edition 2021 authors [Your Name youexample.com] description Simple string utilities license MIT repository https://github.com/yourusername/string_utils# 发布流程cargotestcargodoc--opencargopackagecargopublish练习 24.3综合项目 - 依赖管理工具创建一个工具来分析项目的依赖。参考答案usestd::fs;usestd::path::Path;usetoml::Value;fnmain(){letcargo_tomlfs::read_to_string(Cargo.toml).expect(无法读取 Cargo.toml);letvalue:Valuetoml::from_str(cargo_toml).expect(无法解析 Cargo.toml);ifletSome(deps)value.get(dependencies){println!(依赖列表);ifletSome(table)deps.as_table(){for(name,version)intable{println!( {} {},name,version);}}}ifletSome(dev_deps)value.get(dev-dependencies){println!(\n开发依赖);ifletSome(table)dev_deps.as_table(){for(name,version)intable{println!( {} {},name,version);}}}}本章小结常用 CrateWeb、异步、数据库、CLI、错误处理等领域的推荐质量评估下载量、更新频率、文档、测试覆盖率版本管理语义化版本、Cargo.lock、工作空间依赖更新定期更新、自动化工具、渐进式迁移构建 Crate项目结构、文档、示例、测试发布流程准备、测试、发布、版本管理私有 Registry配置、使用、发布Feature Flags条件编译、可选依赖