rust-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRust Development
Rust 开发
Expert knowledge for modern systems programming with Rust, focusing on memory safety, fearless concurrency, and zero-cost abstractions.
专注于内存安全、无畏并发和零成本抽象的现代Rust系统编程专业知识。
Core Expertise
核心专长
Modern Rust Ecosystem
- Cargo: Build system, package manager, and workspace management
- Rustc: Compiler optimization, target management, and cross-compilation
- Clippy: Linting for idiomatic code and performance improvements
- Rustfmt: Consistent code formatting following Rust style guidelines
- Rust-analyzer: Advanced IDE support with LSP integration
Language Features
- Rust 2024 edition: RPITIT, async fn in traits, impl Trait improvements
- Const generics and compile-time computation
- Generic associated types (GATs)
- Let-else patterns and if-let chains
现代Rust生态系统
- Cargo: 构建系统、包管理器与工作区管理
- Rustc: 编译器优化、目标管理与交叉编译
- Clippy: 针对惯用代码与性能优化的代码检查工具
- Rustfmt: 遵循Rust风格指南的一致代码格式化工具
- Rust-analyzer: 支持LSP的高级IDE工具
语言特性
- Rust 2024版本:RPITIT、trait中的async fn、impl Trait增强
- 常量泛型与编译期计算
- 泛型关联类型(GATs)
- Let-else模式与if-let链式表达式
Key Capabilities
关键能力
Ownership & Memory Safety
- Implement ownership patterns with borrowing and lifetimes
- Design zero-copy abstractions and efficient memory layouts
- Apply RAII patterns through Drop trait and smart pointers (Box, Rc, Arc)
- Leverage interior mutability patterns (Cell, RefCell, Mutex, RwLock)
- Use Pin/Unpin for self-referential structures
Async Programming & Concurrency
- Tokio: Async runtime for high-performance network applications
- async-std: Alternative async runtime with familiar API design
- Futures: Composable async abstractions and stream processing
- Rayon: Data parallelism with work-stealing thread pools
- Design lock-free data structures with atomics and memory ordering
Error Handling & Type Safety
- Design comprehensive error types with thiserror and anyhow
- Implement Result<T, E> and Option<T> patterns effectively
- Use pattern matching for exhaustive error handling
- Apply type-state patterns for compile-time guarantees
Performance Optimization
- Profile with cargo-flamegraph, perf, and criterion benchmarks
- Optimize with SIMD intrinsics and auto-vectorization
- Implement zero-cost abstractions and inline optimizations
- Use unsafe code judiciously with proper safety documentation
Testing & Quality Assurance
- Unit Testing: #[test] modules with assertions
- Integration Testing: tests/ directory for end-to-end validation
- Criterion: Micro-benchmarking with statistical analysis
- Miri: Undefined behavior detection in unsafe code
- Fuzzing: cargo-fuzz for security and robustness testing
所有权与内存安全
- 结合借用与生命周期实现所有权模式
- 设计零拷贝抽象与高效内存布局
- 通过Drop trait与智能指针(Box、Rc、Arc)应用RAII模式
- 利用内部可变性模式(Cell、RefCell、Mutex、RwLock)
- 为自引用结构体使用Pin/Unpin
异步编程与并发
- Tokio: 用于高性能网络应用的异步运行时
- async-std: 具有熟悉API设计的替代异步运行时
- Futures: 可组合的异步抽象与流处理
- Rayon: 基于工作窃取线程池的数据并行处理
- 使用原子操作与内存顺序设计无锁数据结构
错误处理与类型安全
- 使用thiserror与anyhow设计全面的错误类型
- 高效实现Result<T, E>与Option<T>模式
- 使用模式匹配进行穷尽式错误处理
- 应用类型状态模式实现编译期保证
性能优化
- 使用cargo-flamegraph、perf与criterion基准测试工具进行性能分析
- 利用SIMD内在函数与自动向量化进行优化
- 实现零成本抽象与内联优化
- 合理使用unsafe代码并添加适当的安全文档
测试与质量保障
- 单元测试: 带断言的#[test]模块
- 集成测试: 用于端到端验证的tests/目录
- Criterion: 带统计分析的微基准测试
- Miri: 检测unsafe代码中的未定义行为
- 模糊测试: 使用cargo-fuzz进行安全性与健壮性测试
Essential Commands
常用命令
bash
undefinedbash
undefinedProject setup
Project setup
cargo new my-project # Binary crate
cargo new my-lib --lib # Library crate
cargo init # Initialize in existing directory
cargo new my-project # Binary crate
cargo new my-lib --lib # Library crate
cargo init # Initialize in existing directory
Development workflow
Development workflow
cargo build # Debug build
cargo build --release # Optimized build
cargo run # Build and run
cargo run --release # Run optimized
cargo test # Run all tests
cargo test --lib # Library tests only
cargo bench # Run benchmarks
cargo build # Debug build
cargo build --release # Optimized build
cargo run # Build and run
cargo run --release # Run optimized
cargo test # Run all tests
cargo test --lib # Library tests only
cargo bench # Run benchmarks
Code quality
Code quality
cargo clippy # Lint code
cargo clippy -- -W clippy::pedantic # Stricter lints
cargo fmt # Format code
cargo fmt --check # Check formatting
cargo fix # Auto-fix warnings
cargo clippy # Lint code
cargo clippy -- -W clippy::pedantic # Stricter lints
cargo fmt # Format code
cargo fmt --check # Check formatting
cargo fix # Auto-fix warnings
Dependencies
Dependencies
cargo add serde --features derive # Add dependency
cargo update # Update deps
cargo audit # Security audit
cargo deny check # License/advisory check
cargo add serde --features derive # Add dependency
cargo update # Update deps
cargo audit # Security audit
cargo deny check # License/advisory check
Advanced tools
Advanced tools
cargo expand # Macro expansion
cargo flamegraph # Profile with flame graph
cargo doc --open # Generate and open docs
cargo miri test # Check for UB
cargo expand # Macro expansion
cargo flamegraph # Profile with flame graph
cargo doc --open # Generate and open docs
cargo miri test # Check for UB
Cross-compilation
Cross-compilation
rustup target add wasm32-unknown-unknown
cargo build --target wasm32-unknown-unknown
undefinedrustup target add wasm32-unknown-unknown
cargo build --target wasm32-unknown-unknown
undefinedBest Practices
最佳实践
Idiomatic Rust Patterns
rust
// Use iterators over manual loops
let sum: i32 = numbers.iter().filter(|x| **x > 0).sum();
// Prefer combinators for Option/Result
let value = config.get("key")
.and_then(|v| v.parse().ok())
.unwrap_or_default();
// Use pattern matching effectively
match result {
Ok(value) if value > 0 => process(value),
Ok(_) => handle_zero(),
Err(e) => return Err(e.into()),
}
// Let-else for early returns
let Some(config) = load_config() else {
return Err(ConfigError::NotFound);
};Project Structure
my-project/
├── Cargo.toml
├── src/
│ ├── lib.rs # Library root
│ ├── main.rs # Binary entry point
│ ├── error.rs # Error types
│ └── modules/
│ └── mod.rs
├── tests/ # Integration tests
├── benches/ # Benchmarks
└── examples/ # Example programsError Handling
rust
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("parse error: {message}")]
Parse { message: String },
#[error("not found: {0}")]
NotFound(String),
}
pub type Result<T> = std::result::Result<T, AppError>;Common Crates
| Crate | Purpose |
|---|---|
| Serialization/deserialization |
| Async runtime |
| HTTP client |
| Async SQL |
| CLI argument parsing |
| Logging/diagnostics |
| Application errors |
| Library errors |
For detailed async patterns, unsafe code guidelines, WebAssembly compilation, embedded development, and advanced debugging, see REFERENCE.md.
惯用Rust模式
rust
// Use iterators over manual loops
let sum: i32 = numbers.iter().filter(|x| **x > 0).sum();
// Prefer combinators for Option/Result
let value = config.get("key")
.and_then(|v| v.parse().ok())
.unwrap_or_default();
// Use pattern matching effectively
match result {
Ok(value) if value > 0 => process(value),
Ok(_) => handle_zero(),
Err(e) => return Err(e.into()),
}
// Let-else for early returns
let Some(config) = load_config() else {
return Err(ConfigError::NotFound);
};项目结构
my-project/
├── Cargo.toml
├── src/
│ ├── lib.rs # Library root
│ ├── main.rs # Binary entry point
│ ├── error.rs # Error types
│ └── modules/
│ └── mod.rs
├── tests/ # Integration tests
├── benches/ # Benchmarks
└── examples/ # Example programs错误处理
rust
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("parse error: {message}")]
Parse { message: String },
#[error("not found: {0}")]
NotFound(String),
}
pub type Result<T> = std::result::Result<T, AppError>;常用Crates
| Crate | 用途 |
|---|---|
| 序列化/反序列化 |
| 异步运行时 |
| HTTP客户端 |
| 异步SQL |
| CLI参数解析 |
| 日志/诊断 |
| 应用错误处理 |
| 库错误处理 |
关于详细的异步模式、unsafe代码指南、WebAssembly编译、嵌入式开发与高级调试,请参考REFERENCE.md。