rust-ecosystem
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAsync Runtimes
异步运行时
| Runtime | Characteristics | Use Case |
|---|---|---|
| tokio | Most popular, feature-rich | General async applications |
| async-std | std-like API | Prefer std-style APIs |
| smol | Minimal, embeddable | Lightweight applications |
| async-executors | Unified interface | Need runtime portability |
toml
undefined| 运行时 | 特性 | 适用场景 |
|---|---|---|
| tokio | 最受欢迎、功能丰富 | 通用异步应用 |
| async-std | 类std API | 偏好std风格API的场景 |
| smol | 轻量、可嵌入 | 轻量级应用 |
| async-executors | 统一接口 | 需要运行时可移植性的场景 |
toml
undefinedWeb services
Web services
tokio = { version = "1", features = ["full"] }
axum = "0.7"
tokio = { version = "1", features = ["full"] }
axum = "0.7"
Lightweight
Lightweight
async-std = "1"
async-std = "1"
Minimal
Minimal
smol = "2"
undefinedsmol = "2"
undefinedSolution Patterns
解决方案模式
Pattern 1: Web Service Stack
模式1:Web服务技术栈
toml
[dependencies]toml
[dependencies]Async runtime
Async runtime
tokio = { version = "1", features = ["full"] }
tokio = { version = "1", features = ["full"] }
Web framework
Web framework
axum = "0.7"
axum = "0.7"
Database
Database
sqlx = { version = "0.7", features = ["runtime-tokio", "postgres"] }
sqlx = { version = "0.7", features = ["runtime-tokio", "postgres"] }
Serialization
Serialization
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Error handling
Error handling
anyhow = "1"
thiserror = "1"
anyhow = "1"
thiserror = "1"
Tracing
Tracing
tracing = "0.1"
tracing-subscriber = "0.3"
undefinedtracing = "0.1"
tracing-subscriber = "0.3"
undefinedPattern 2: CLI Tool Stack
模式2:CLI工具技术栈
toml
[dependencies]toml
[dependencies]Argument parsing
Argument parsing
clap = { version = "4", features = ["derive"] }
clap = { version = "4", features = ["derive"] }
Error handling
Error handling
anyhow = "1"
anyhow = "1"
Config
Config
config = "0.13"
dotenvy = "0.15"
config = "0.13"
dotenvy = "0.15"
Progress
Progress
indicatif = "0.17"
indicatif = "0.17"
Terminal colors
Terminal colors
colored = "2"
undefinedcolored = "2"
undefinedPattern 3: Data Processing
模式3:数据处理
toml
[dependencies]toml
[dependencies]Parallelism
Parallelism
rayon = "1"
rayon = "1"
CSV
CSV
csv = "1"
csv = "1"
Serialization
Serialization
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
HTTP client
HTTP client
reqwest = { version = "0.11", features = ["json", "blocking"] }
undefinedreqwest = { version = "0.11", features = ["json", "blocking"] }
undefinedWeb Frameworks
Web框架
| Framework | Characteristics | Performance |
|---|---|---|
| axum | Tower middleware, type-safe | High |
| actix-web | Highest performance | Highest |
| rocket | Developer-friendly | Medium |
| warp | Compositional, filters | High |
rust
// axum example
use axum::{Router, routing::get, Json};
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u64,
name: String,
}
async fn get_user() -> Json<User> {
Json(User {
id: 1,
name: "Alice".to_string(),
})
}
let app = Router::new()
.route("/user", get(get_user));| 框架 | 特性 | 性能 |
|---|---|---|
| axum | Tower中间件、类型安全 | 高 |
| actix-web | 性能最优 | 最高 |
| rocket | 开发者友好 | 中等 |
| warp | 组合式、基于过滤器 | 高 |
rust
// axum example
use axum::{Router, routing::get, Json};
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u64,
name: String,
}
async fn get_user() -> Json<User> {
Json(User {
id: 1,
name: "Alice".to_string(),
})
}
let app = Router::new()
.route("/user", get(get_user));Serialization
序列化
| Library | Characteristics | Performance |
|---|---|---|
| serde | Standard choice | High |
| bincode | Binary, compact | Highest |
| postcard | no_std, embedded | High |
| ron | Readable format | Medium |
rust
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct User {
id: u64,
name: String,
}
// JSON
let json = serde_json::to_string(&user)?;
let user: User = serde_json::from_str(&json)?;
// Binary (more efficient)
let bytes = bincode::serialize(&user)?;
let user: User = bincode::deserialize(&bytes)?;| 库 | 特性 | 性能 |
|---|---|---|
| serde | 标准选择 | 高 |
| bincode | 二进制、紧凑 | 最高 |
| postcard | no_std、嵌入式 | 高 |
| ron | 可读格式 | 中等 |
rust
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct User {
id: u64,
name: String,
}
// JSON
let json = serde_json::to_string(&user)?;
let user: User = serde_json::from_str(&json)?;
// Binary (more efficient)
let bytes = bincode::serialize(&user)?;
let user: User = bincode::deserialize(&bytes)?;HTTP Clients
HTTP客户端
| Library | Characteristics |
|---|---|
| reqwest | Most popular, easy to use |
| ureq | Sync, simple |
| surf | Async, modern |
| hyper | Low-level, flexible |
rust
// reqwest - async
let response = reqwest::Client::new()
.post("https://api.example.com")
.json(&payload)
.send()
.await?
.json::<Response>()
.await?;
// ureq - sync (no async runtime needed)
let response: Response = ureq::post("https://api.example.com")
.send_json(&payload)?
.into_json()?;| 库 | 特性 |
|---|---|
| reqwest | 最受欢迎、易用 |
| ureq | 同步、简洁 |
| surf | 异步、现代 |
| hyper | 底层、灵活 |
rust
// reqwest - async
let response = reqwest::Client::new()
.post("https://api.example.com")
.json(&payload)
.send()
.await?
.json::<Response>()
.await?;
// ureq - sync (no async runtime needed)
let response: Response = ureq::post("https://api.example.com")
.send_json(&payload)?
.into_json()?;Databases
数据库
| Type | Library |
|---|---|
| ORM | sqlx, diesel, sea-orm |
| Raw SQL | sqlx, tokio-postgres |
| NoSQL | mongodb, redis |
| Connection pool | sqlx, deadpool, r2d2 |
rust
// sqlx with compile-time checked queries
use sqlx::PgPool;
let pool = PgPool::connect(&database_url).await?;
let user = sqlx::query_as!(
User,
"SELECT id, name FROM users WHERE id = $1",
user_id
)
.fetch_one(&pool)
.await?;| 类型 | 库 |
|---|---|
| ORM | sqlx, diesel, sea-orm |
| 原生SQL | sqlx, tokio-postgres |
| NoSQL | mongodb, redis |
| 连接池 | sqlx, deadpool, r2d2 |
rust
// sqlx with compile-time checked queries
use sqlx::PgPool;
let pool = PgPool::connect(&database_url).await?;
let user = sqlx::query_as!(
User,
"SELECT id, name FROM users WHERE id = $1",
user_id
)
.fetch_one(&pool)
.await?;Concurrency & Parallelism
并发与并行
| Scenario | Recommendation |
|---|---|
| Data parallelism | rayon |
| Work stealing | crossbeam, tokio |
| Channels | tokio::sync, crossbeam, flume |
| Atomics | std::sync::atomic |
rust
// rayon - easy parallelism
use rayon::prelude::*;
let sum: i32 = data
.par_iter()
.map(|x| expensive_computation(x))
.sum();| 场景 | 推荐方案 |
|---|---|
| 数据并行 | rayon |
| 工作窃取 | crossbeam, tokio |
| 通道 | tokio::sync, crossbeam, flume |
| 原子操作 | std::sync::atomic |
rust
// rayon - easy parallelism
use rayon::prelude::*;
let sum: i32 = data
.par_iter()
.map(|x| expensive_computation(x))
.sum();Error Handling
错误处理
| Library | Use Case |
|---|---|
| thiserror | Library error types |
| anyhow | Application error propagation |
| snafu | Structured errors |
rust
// thiserror - for libraries
use thiserror::Error;
#[derive(Error, Debug)]
pub enum MyError {
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("Invalid data: {msg}")]
Invalid { msg: String },
}
// anyhow - for applications
use anyhow::{Context, Result};
fn load_config() -> Result<Config> {
let content = std::fs::read_to_string("config.toml")
.context("failed to read config file")?;
toml::from_str(&content)
.context("failed to parse config")
}| 库 | 适用场景 |
|---|---|
| thiserror | 库错误类型定义 |
| anyhow | 应用错误传播 |
| snafu | 结构化错误 |
rust
// thiserror - for libraries
use thiserror::Error;
#[derive(Error, Debug)]
pub enum MyError {
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("Invalid data: {msg}")]
Invalid { msg: String },
}
// anyhow - for applications
use anyhow::{Context, Result};
fn load_config() -> Result<Config> {
let content = std::fs::read_to_string("config.toml")
.context("failed to read config file")?;
toml::from_str(&content)
.context("failed to parse config")
}Common Tools
常用工具
| Scenario | Library |
|---|---|
| CLI parsing | clap (v4), structopt |
| Logging | tracing, log |
| Config | config, dotenvy |
| Testing | tempfile, rstest, proptest |
| Time | chrono, time |
| Random | rand |
| Regex | regex |
| 场景 | 库 |
|---|---|
| CLI参数解析 | clap (v4), structopt |
| 日志 | tracing, log |
| 配置 | config, dotenvy |
| 测试 | tempfile, rstest, proptest |
| 时间处理 | chrono, time |
| 随机数 | rand |
| 正则表达式 | regex |
Crate Selection Principles
Crate选型原则
- Active maintenance: Check GitHub activity, recent updates
- Download count: Reference crates.io downloads
- MSRV: Minimum Supported Rust Version compatibility
- Dependencies: Number and security of dependencies
- Documentation: Complete docs and examples
- License: MIT/Apache2 compatibility
bash
undefined- 活跃维护:查看GitHub活跃度、最近更新记录
- 下载量:参考crates.io下载数据
- MSRV:最低支持Rust版本兼容性
- 依赖项:依赖数量与安全性
- 文档:完善的文档与示例
- 许可证:MIT/Apache2兼容性
bash
undefinedCheck crate info
Check crate info
cargo info <crate-name>
cargo info <crate-name>
Check dependencies
Check dependencies
cargo tree
cargo tree
Security audit
Security audit
cargo audit
cargo audit
License check
License check
cargo deny check licenses
undefinedcargo deny check licenses
undefinedWorkflow
工作流程
Step 1: Identify Need
步骤1:明确需求
What problem to solve?
→ Web service? Choose framework (axum/actix)
→ CLI tool? Use clap + anyhow
→ Data processing? Use rayon
→ Database access? Use sqlx要解决什么问题?
→ Web服务?选择框架(axum/actix)
→ CLI工具?使用clap + anyhow
→ 数据处理?使用rayon
→ 数据库访问?使用sqlxStep 2: Evaluate Options
步骤2:评估选项
Check:
→ crates.io download count
→ GitHub stars and activity
→ Documentation quality
→ Recent releases
→ Community support检查:
→ crates.io下载量
→ GitHub星数与活跃度
→ 文档质量
→ 最近发布版本
→ 社区支持Step 3: Verify Safety
步骤3:验证安全性
bash
undefinedbash
undefinedSecurity audit
Security audit
cargo audit
cargo audit
License compatibility
License compatibility
cargo deny check
cargo deny check
Dependency tree
Dependency tree
cargo tree -i <crate>
undefinedcargo tree -i <crate>
undefinedDeprecated Patterns → Modern
过时模式→现代替代方案
| Deprecated | Modern | Reason |
|---|---|---|
| | std built-in |
| | New API |
| | More popular |
| | Simpler imports |
| 过时方案 | 现代替代 | 原因 |
|---|---|---|
| | 标准库内置 |
| | 新API |
| | 更受欢迎 |
| | 导入更简单 |
Quick Reference
速查指南
| Scenario | Recommended Stack |
|---|---|
| Web service | axum + tokio + sqlx + serde |
| CLI tool | clap + anyhow + config |
| Serialization | serde + (json/bincode/postcard) |
| Parallel compute | rayon |
| Config management | config + dotenvy |
| Logging | tracing + tracing-subscriber |
| Testing | tempfile + rstest + proptest |
| Date/time | chrono or time |
| 场景 | 推荐技术栈 |
|---|---|
| Web服务 | axum + tokio + sqlx + serde |
| CLI工具 | clap + anyhow + config |
| 序列化 | serde + (json/bincode/postcard) |
| 并行计算 | rayon |
| 配置管理 | config + dotenvy |
| 日志 | tracing + tracing-subscriber |
| 测试 | tempfile + rstest + proptest |
| 日期/时间 | chrono or time |
Review Checklist
选型检查清单
When selecting crates:
- Crate is actively maintained (updated within 6 months)
- Good documentation and examples
- Reasonable dependency count
- No known security issues (cargo audit)
- Compatible license (MIT/Apache2)
- MSRV compatible with project
- High download count and community usage
- Stable API (1.0+ or widely used)
选择crate时:
- Crate处于活跃维护状态(6个月内有更新)
- 具备完善的文档与示例
- 依赖数量合理
- 无已知安全问题(通过cargo audit验证)
- 许可证兼容(MIT/Apache2)
- MSRV与项目兼容
- 下载量高、社区广泛使用
- API稳定(1.0+或被广泛采用)
Verification Commands
验证命令
bash
undefinedbash
undefinedSearch crates
Search crates
cargo search <keyword>
cargo search <keyword>
Get crate info
Get crate info
cargo info <crate-name>
cargo info <crate-name>
Check dependencies
Check dependencies
cargo tree
cargo tree
Security audit
Security audit
cargo audit
cargo audit
License check
License check
cargo deny check
cargo deny check
Check for updates
Check for updates
cargo outdated
undefinedcargo outdated
undefinedCommon Pitfalls
常见陷阱
1. Too Many Dependencies
1. 依赖过多
Symptom: Long compile times, dependency conflicts
toml
undefined症状:编译时间长、依赖冲突
toml
undefined❌ Avoid: unnecessary dependencies
❌ 避免:不必要的依赖
[dependencies]
[dependencies]
Don't need full tokio if only using channels
仅使用通道时无需完整tokio
tokio = { version = "1", features = ["full"] }
tokio = { version = "1", features = ["full"] }
✅ Better: minimal features
✅ 更佳方案:最小化特性
tokio = { version = "1", features = ["sync"] }
undefinedtokio = { version = "1", features = ["sync"] }
undefined2. Unmaintained Crates
2. 无人维护的Crate
Symptom: Security vulnerabilities, incompatibilities
bash
undefined症状:安全漏洞、兼容性问题
bash
undefinedCheck last update
检查最后更新时间
cargo info <crate-name>
cargo info <crate-name>
Check for alternatives
寻找替代方案
cargo search <similar-crate>
undefinedcargo search <similar-crate>
undefined3. Version Conflicts
3. 版本冲突
Symptom: Build failures, duplicate dependencies
bash
undefined症状:构建失败、重复依赖
bash
undefinedDiagnose conflicts
诊断冲突
cargo tree -d
cargo tree -d
Use same version across workspace
工作空间内统一版本
[workspace.dependencies]
serde = "1"
undefined[workspace.dependencies]
serde = "1"
undefinedRelated Skills
相关技能
- rust-async - Async runtime patterns
- rust-web - Web framework usage
- rust-error - Error handling libraries
- rust-testing - Testing libraries
- rust-performance - Performance-critical crates
- rust-async - 异步运行时模式
- rust-web - Web框架使用
- rust-error - 错误处理库
- rust-testing - 测试库
- rust-performance - 性能关键型crate
Localized Reference
本地化参考
- Chinese version: SKILL_ZH.md - 完整中文版本,包含所有内容
- 中文版本:SKILL_ZH.md - 完整中文版本,包含所有内容