rust-pro
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRust 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 unless necessary. Use
.clone()orArc<Mutex<T>>for shared state only when message passing (RwLock<T>) is not viable.mpsc - Error Handling: Use with
Result<T, E>for libraries andthiserrorfor applications. Never useanyhowin production code; use.unwrap()with a context message or.expect()operator.? - Async Runtime: Default to for general purpose apps. Use
tokiofor parallel execution of futures.join_all - Type System: Leverage traits and generics for zero-cost abstractions. Use pattern to enforce validation at compile time.
New Type
- 所有权与借用:严格遵守所有权规则。除非必要,避免使用。仅当消息传递(
.clone())不可行时,才使用mpsc或Arc<Mutex<T>>处理共享状态。RwLock<T> - 错误处理:库开发使用搭配
Result<T, E>,应用开发使用thiserror。生产代码中绝不要使用anyhow;应使用带上下文信息的.unwrap()或.expect()运算符。? - 异步运行时:通用应用默认使用。使用
tokio并行执行 futures。join_all - 类型系统:利用 trait 和泛型实现零成本抽象。使用“New Type”模式在编译时强制验证。
2. Toolchain & Ecosystem
2. 工具链与生态系统
- Build System:
cargo - Linter: (Treat warnings as errors in CI)
clippy - Formatter:
rustfmt - Testing: Built-in and
#[test]. Usecargo testfor mocking traits.mockall
- 构建系统:
cargo - 代码检查工具:(在CI中将警告视为错误)
clippy - 代码格式化工具:
rustfmt - 测试:内置的和
#[test]。使用cargo test进行 trait 模拟。mockall
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.rstext
my_crate/
├── Cargo.toml
├── src/
│ ├── main.rs # 二进制程序入口
│ ├── lib.rs # 库入口
│ ├── bin/ # 额外二进制程序
│ ├── models/ # 数据结构
│ ├── error.rs # 集中式错误定义
│ └── utils.rs # 辅助函数
└── tests/ # 集成测试
└── integration_test.rs4. Common Dependencies (The Standard Stack)
4. 常用依赖(标准技术栈)
- Async: ,
tokiofutures - Web: or
axumactix-web - Serialization: ,
serdeserde_json - Error Handling: ,
anyhowthiserror - Tracing/Logging: ,
tracingtracing-subscriber - config: crate for environment management
config
- 异步:、
tokiofutures - Web:或
axumactix-web - 序列化:、
serdeserde_json - 错误处理:、
anyhowthiserror - 追踪/日志:、
tracingtracing-subscriber - 配置:使用crate 进行环境管理
config
5. Security & Performance
5. 安全与性能
- Memory: Use only when ownership is needed; prefer
Stringfor function arguments.&str - Unsafe: Avoid blocks unless absolutely necessary and documented with
unsafecomment explaining why it holds.// SAFETY: - Vectors: Pre-allocate vectors with if size is known.
Vec::with_capacity(n)
- 内存:仅在需要所有权时使用;函数参数优先使用
String。&str - 不安全代码:除非绝对必要,否则避免代码块,且必须添加
unsafe注释说明其安全性的原因。// SAFETY: - 向量:如果已知大小,使用预分配向量空间。
Vec::with_capacity(n)
6. Implementation Workflow
6. 实现工作流
- Define Types: Start with and
structdefinitions.enum - Define Traits: Outline behavior using traits.
- Implement Logic: Implement traits for types.
- Wire up: Connect components in or
main.rs.lib.rs - Test: Write unit tests alongside code and integration tests in .
tests/
Anti-Patterns to Avoid:
- Excessive use of (prefer generics with static dispatch).
Box<dyn Trait> - Ignoring (always handle or propagate).
Result - Global mutable state (use dependency injection or actor pattern).
- 定义类型:从和
struct定义开始。enum - 定义Trait:使用 trait 勾勒行为。
- 实现逻辑:为类型实现 trait。
- 组件连接:在或
main.rs中连接各组件。lib.rs - 测试:在代码旁编写单元测试,并在目录中编写集成测试。
tests/
需避免的反模式:
- 过度使用(优先使用静态分发的泛型)。
Box<dyn Trait> - 忽略(始终处理或传播错误)。
Result - 全局可变状态(使用依赖注入或 actor 模式)。