rust-ecosystem

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Async Runtimes

异步运行时

RuntimeCharacteristicsUse Case
tokioMost popular, feature-richGeneral async applications
async-stdstd-like APIPrefer std-style APIs
smolMinimal, embeddableLightweight applications
async-executorsUnified interfaceNeed runtime portability
toml
undefined
运行时特性适用场景
tokio最受欢迎、功能丰富通用异步应用
async-std类std API偏好std风格API的场景
smol轻量、可嵌入轻量级应用
async-executors统一接口需要运行时可移植性的场景
toml
undefined

Web 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"
undefined
smol = "2"
undefined

Solution 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"
undefined
tracing = "0.1" tracing-subscriber = "0.3"
undefined

Pattern 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"
undefined
colored = "2"
undefined

Pattern 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"] }
undefined
reqwest = { version = "0.11", features = ["json", "blocking"] }
undefined

Web Frameworks

Web框架

FrameworkCharacteristicsPerformance
axumTower middleware, type-safeHigh
actix-webHighest performanceHighest
rocketDeveloper-friendlyMedium
warpCompositional, filtersHigh
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));
框架特性性能
axumTower中间件、类型安全
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

序列化

LibraryCharacteristicsPerformance
serdeStandard choiceHigh
bincodeBinary, compactHighest
postcardno_std, embeddedHigh
ronReadable formatMedium
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二进制、紧凑最高
postcardno_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客户端

LibraryCharacteristics
reqwestMost popular, easy to use
ureqSync, simple
surfAsync, modern
hyperLow-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

数据库

TypeLibrary
ORMsqlx, diesel, sea-orm
Raw SQLsqlx, tokio-postgres
NoSQLmongodb, redis
Connection poolsqlx, 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?;
类型
ORMsqlx, diesel, sea-orm
原生SQLsqlx, tokio-postgres
NoSQLmongodb, 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

并发与并行

ScenarioRecommendation
Data parallelismrayon
Work stealingcrossbeam, tokio
Channelstokio::sync, crossbeam, flume
Atomicsstd::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

错误处理

LibraryUse Case
thiserrorLibrary error types
anyhowApplication error propagation
snafuStructured 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

常用工具

ScenarioLibrary
CLI parsingclap (v4), structopt
Loggingtracing, log
Configconfig, dotenvy
Testingtempfile, rstest, proptest
Timechrono, time
Randomrand
Regexregex
场景
CLI参数解析clap (v4), structopt
日志tracing, log
配置config, dotenvy
测试tempfile, rstest, proptest
时间处理chrono, time
随机数rand
正则表达式regex

Crate Selection Principles

Crate选型原则

  1. Active maintenance: Check GitHub activity, recent updates
  2. Download count: Reference crates.io downloads
  3. MSRV: Minimum Supported Rust Version compatibility
  4. Dependencies: Number and security of dependencies
  5. Documentation: Complete docs and examples
  6. License: MIT/Apache2 compatibility
bash
undefined
  1. 活跃维护:查看GitHub活跃度、最近更新记录
  2. 下载量:参考crates.io下载数据
  3. MSRV:最低支持Rust版本兼容性
  4. 依赖项:依赖数量与安全性
  5. 文档:完善的文档与示例
  6. 许可证:MIT/Apache2兼容性
bash
undefined

Check 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
undefined
cargo deny check licenses
undefined

Workflow

工作流程

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
  → 数据库访问?使用sqlx

Step 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
undefined
bash
undefined

Security 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>
undefined
cargo tree -i <crate>
undefined

Deprecated Patterns → Modern

过时模式→现代替代方案

DeprecatedModernReason
lazy_static
std::sync::OnceLock
std built-in
rand::thread_rng
rand::rng()
New API
failure
thiserror
+
anyhow
More popular
serde_derive
serde
(unified)
Simpler imports
过时方案现代替代原因
lazy_static
std::sync::OnceLock
标准库内置
rand::thread_rng
rand::rng()
新API
failure
thiserror
+
anyhow
更受欢迎
serde_derive
serde
(统一集成)
导入更简单

Quick Reference

速查指南

ScenarioRecommended Stack
Web serviceaxum + tokio + sqlx + serde
CLI toolclap + anyhow + config
Serializationserde + (json/bincode/postcard)
Parallel computerayon
Config managementconfig + dotenvy
Loggingtracing + tracing-subscriber
Testingtempfile + rstest + proptest
Date/timechrono 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
undefined
bash
undefined

Search 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
undefined
cargo outdated
undefined

Common 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"] }
undefined
tokio = { version = "1", features = ["sync"] }
undefined

2. Unmaintained Crates

2. 无人维护的Crate

Symptom: Security vulnerabilities, incompatibilities
bash
undefined
症状:安全漏洞、兼容性问题
bash
undefined

Check last update

检查最后更新时间

cargo info <crate-name>
cargo info <crate-name>

Check for alternatives

寻找替代方案

cargo search <similar-crate>
undefined
cargo search <similar-crate>
undefined

3. Version Conflicts

3. 版本冲突

Symptom: Build failures, duplicate dependencies
bash
undefined
症状:构建失败、重复依赖
bash
undefined

Diagnose conflicts

诊断冲突

cargo tree -d
cargo tree -d

Use same version across workspace

工作空间内统一版本

[workspace.dependencies] serde = "1"
undefined
[workspace.dependencies] serde = "1"
undefined

Related 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 - 完整中文版本,包含所有内容