rust-pro

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rust Professional Development

Rust专业开发

Goal: Write idiomatic, high-performance, and memory-safe Rust code following standard community practices (The Rust Way).
目标:遵循Rust社区标准实践(Rust之道),编写地道、高性能且内存安全的Rust代码。

1. Core Principles

1. 核心原则

  • Ownership & Borrowing: strictly enforce ownership rules. Avoid
    .clone()
    unless necessary. Use
    Arc<Mutex<T>>
    or
    RwLock<T>
    for shared state only when message passing (
    mpsc
    ) is not viable.
  • Error Handling: Use
    Result<T, E>
    with
    thiserror
    for libraries and
    anyhow
    for applications. Never use
    .unwrap()
    in production code; use
    .expect()
    with a context message or
    ?
    operator.
  • Async Runtime: Default to
    tokio
    for general purpose apps. Use
    join_all
    for parallel execution of futures.
  • Type System: Leverage traits and generics for zero-cost abstractions. Use
    New Type
    pattern to enforce validation at compile time.
  • 所有权与借用:严格遵守所有权规则。除非必要,避免使用
    .clone()
    。仅当消息传递(
    mpsc
    )不可行时,才使用
    Arc<Mutex<T>>
    RwLock<T>
    处理共享状态。
  • 错误处理:库开发使用
    Result<T, E>
    搭配
    thiserror
    ,应用开发使用
    anyhow
    。生产代码中绝不要使用
    .unwrap()
    ;应使用带上下文信息的
    .expect()
    ?
    运算符。
  • 异步运行时:通用应用默认使用
    tokio
    。使用
    join_all
    并行执行 futures。
  • 类型系统:利用 trait 和泛型实现零成本抽象。使用“New Type”模式在编译时强制验证。

2. Toolchain & Ecosystem

2. 工具链与生态系统

  • Build System:
    cargo
  • Linter:
    clippy
    (Treat warnings as errors in CI)
  • Formatter:
    rustfmt
  • Testing: Built-in
    #[test]
    and
    cargo test
    . Use
    mockall
    for mocking traits.
  • 构建系统
    cargo
  • 代码检查工具
    clippy
    (在CI中将警告视为错误)
  • 代码格式化工具
    rustfmt
  • 测试:内置的
    #[test]
    cargo test
    。使用
    mockall
    进行 trait 模拟。

3. Recommended Project Structure

3. 推荐项目结构

text
my_crate/
├── Cargo.toml
├── src/
│   ├── main.rs          # Binary entry point
│   ├── lib.rs           # Library entry point
│   ├── bin/             # Additional binaries
│   ├── models/          # Data structures
│   ├── error.rs         # Central error definition
│   └── utils.rs         # Helper functions
└── tests/               # Integration tests
    └── integration_test.rs
text
my_crate/
├── Cargo.toml
├── src/
│   ├── main.rs          # 二进制程序入口
│   ├── lib.rs           # 库入口
│   ├── bin/             # 额外二进制程序
│   ├── models/          # 数据结构
│   ├── error.rs         # 集中式错误定义
│   └── utils.rs         # 辅助函数
└── tests/               # 集成测试
    └── integration_test.rs

4. Common Dependencies (The Standard Stack)

4. 常用依赖(标准技术栈)

  • Async:
    tokio
    ,
    futures
  • Web:
    axum
    or
    actix-web
  • Serialization:
    serde
    ,
    serde_json
  • Error Handling:
    anyhow
    ,
    thiserror
  • Tracing/Logging:
    tracing
    ,
    tracing-subscriber
  • config:
    config
    crate for environment management
  • 异步
    tokio
    futures
  • Web
    axum
    actix-web
  • 序列化
    serde
    serde_json
  • 错误处理
    anyhow
    thiserror
  • 追踪/日志
    tracing
    tracing-subscriber
  • 配置:使用
    config
    crate 进行环境管理

5. Security & Performance

5. 安全与性能

  • Memory: Use
    String
    only when ownership is needed; prefer
    &str
    for function arguments.
  • Unsafe: Avoid
    unsafe
    blocks unless absolutely necessary and documented with
    // SAFETY:
    comment explaining why it holds.
  • Vectors: Pre-allocate vectors with
    Vec::with_capacity(n)
    if size is known.
  • 内存:仅在需要所有权时使用
    String
    ;函数参数优先使用
    &str
  • 不安全代码:除非绝对必要,否则避免
    unsafe
    代码块,且必须添加
    // SAFETY:
    注释说明其安全性的原因。
  • 向量:如果已知大小,使用
    Vec::with_capacity(n)
    预分配向量空间。

6. Implementation Workflow

6. 实现工作流

  1. Define Types: Start with
    struct
    and
    enum
    definitions.
  2. Define Traits: Outline behavior using traits.
  3. Implement Logic: Implement traits for types.
  4. Wire up: Connect components in
    main.rs
    or
    lib.rs
    .
  5. Test: Write unit tests alongside code and integration tests in
    tests/
    .

Anti-Patterns to Avoid:
  • Excessive use of
    Box<dyn Trait>
    (prefer generics with static dispatch).
  • Ignoring
    Result
    (always handle or propagate).
  • Global mutable state (use dependency injection or actor pattern).
  1. 定义类型:从
    struct
    enum
    定义开始。
  2. 定义Trait:使用 trait 勾勒行为。
  3. 实现逻辑:为类型实现 trait。
  4. 组件连接:在
    main.rs
    lib.rs
    中连接各组件。
  5. 测试:在代码旁编写单元测试,并在
    tests/
    目录中编写集成测试。

需避免的反模式
  • 过度使用
    Box<dyn Trait>
    (优先使用静态分发的泛型)。
  • 忽略
    Result
    (始终处理或传播错误)。
  • 全局可变状态(使用依赖注入或 actor 模式)。