moai-lang-rust

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Quick Reference (30 seconds)

快速参考(30秒)

Rust 1.92+ Development Specialist with deep patterns for high-performance, memory-safe applications.
Auto-Triggers:
.rs
,
Cargo.toml
, async/await, Tokio, Axum, SQLx, serde, lifetimes, traits
Core Use Cases:
  • High-performance REST APIs and microservices
  • Memory-safe concurrent systems
  • CLI tools and system utilities
  • WebAssembly applications
  • Low-latency networking services
Quick Patterns:
Axum REST API: Create Router with route macro chaining path and handler. Add with_state for shared state. Bind TcpListener with tokio::net and serve with axum::serve.
Async Handler with SQLx: Define async handler function taking State extractor for AppState and Path extractor for id. Use sqlx::query_as! macro with SQL string and bind parameters. Call fetch_optional on pool, await, and use ok_or for error conversion. Return Json wrapped result.

Rust 1.92+开发专家,掌握构建高性能、内存安全应用的深度模式。
自动触发:.rs、Cargo.toml、async/await、Tokio、Axum、SQLx、serde、lifetimes、traits
核心适用场景:
  • 高性能REST API与微服务
  • 内存安全的并发系统
  • CLI工具与系统实用程序
  • WebAssembly应用程序
  • 低延迟网络服务
快速模式:
Axum REST API:使用route宏链式调用路径和处理器创建Router。添加with_state以实现状态共享。通过tokio::net绑定TcpListener,并用axum::serve启动服务。
带SQLx的异步处理器:定义异步处理器函数,接收用于AppState的State提取器和用于id的Path提取器。使用sqlx::query_as!宏配合SQL语句和绑定参数。在连接池上调用fetch_optional,等待结果后用ok_or转换错误。返回包裹在Json中的结果。

Implementation Guide (5 minutes)

实现指南(5分钟)

Rust 1.92 Features

Rust 1.92特性

Modern Rust Features:
  • Rust 2024 Edition available (released with Rust 1.85)
  • Async traits in stable (no more async-trait crate needed)
  • Const generics for compile-time array sizing
  • let-else for pattern matching with early return
  • Improved borrow checker with polonius
Async Traits (Stable): Define trait with async fn signatures. Implement trait for concrete types with async fn implementations. Call sqlx macros directly in trait methods.
Let-Else Pattern: Use let Some(value) = option else with return for early exit. Chain multiple let-else statements for sequential validation. Return error types in else blocks.
现代Rust特性:
  • Rust 2024版本已可用(随Rust 1.85发布)
  • 稳定版支持异步特征(async traits),无需再使用async-trait crate
  • 常量泛型用于编译期数组大小定义
  • let-else模式匹配支持提前返回
  • 改进的借用检查器(polonius)
异步特征(稳定版):定义包含async fn签名的特征。为具体类型实现带有async fn的特征。可在特征方法中直接调用sqlx宏。
Let-Else模式:使用let Some(value) = option else搭配return实现提前退出。链式调用多个let-else语句进行顺序验证。在else块中返回错误类型。

Web Framework: Axum 0.8

Web框架:Axum 0.8

Installation: In Cargo.toml dependencies section, add axum version 0.8, tokio version 1.48 with full features, and tower-http version 0.6 with cors and trace features.
Complete API Setup: Import extractors from axum::extract and routing macros. Define Clone-derive AppState struct holding PgPool. In tokio::main async main, create pool with PgPoolOptions setting max_connections and connecting with DATABASE_URL from env. Build Router with route chains for paths and handlers, add CorsLayer, and call with_state. Bind TcpListener and call axum::serve.
Handler Patterns: Define async handlers taking State, Path, and Query extractors with appropriate types. Use sqlx::query_as! for type-safe queries with positional binds. Return Result with Json success and AppError failure.
安装:在Cargo.toml的依赖项部分,添加版本为0.8的axum、带有full特性的1.48版本tokio,以及带有cors和trace特性的0.6版本tower-http。
完整API设置:从axum::extract导入提取器,导入路由宏。定义派生Clone的AppState结构体,用于存储PgPool。在tokio::main异步主函数中,使用PgPoolOptions设置最大连接数,并通过环境变量DATABASE_URL创建连接池。使用路由链构建Router,添加CorsLayer,并调用with_state。绑定TcpListener后调用axum::serve启动服务。
处理器模式:定义接收State、Path和Query提取器的异步处理器,使用合适的类型。使用sqlx::query_as!进行类型安全的查询,支持位置绑定。返回包含成功Json和失败AppError的Result。

Async Runtime: Tokio 1.48

异步运行时:Tokio 1.48

Task Spawning and Channels: Create mpsc channel with capacity. Spawn worker tasks with tokio::spawn that receive from channel in loop. For timeouts, use tokio::select! macro with operation branch and sleep branch, returning error on timeout.
任务生成与通道:创建指定容量的mpsc通道。使用tokio::spawn生成工作任务,在循环中从通道接收消息。处理超时场景时,使用tokio::select!宏,包含操作分支和睡眠分支,超时返回错误。

Database: SQLx 0.8

数据库:SQLx 0.8

Type-Safe Queries: Derive sqlx::FromRow on structs for automatic mapping. Use query_as! macro for compile-time checked queries. Call fetch_one or fetch_optional on pool. For transactions, call pool.begin, execute queries on transaction reference, and call tx.commit.
类型安全查询:在结构体上派生sqlx::FromRow以实现自动映射。使用query_as!宏进行编译期检查的查询。在连接池上调用fetch_one或fetch_optional。处理事务时,调用pool.begin,在事务引用上执行查询,最后调用tx.commit提交。

Serialization: Serde 1.0

序列化:Serde 1.0

Derive Serialize and Deserialize on structs. Use serde attribute with rename_all for case conversion. Use rename attribute for field-specific naming. Use skip_serializing_if with Option::is_none. Use default attribute for default values.
在结构体上派生Serialize和Deserialize。使用serde属性的rename_all进行大小写转换。使用rename属性指定字段的自定义名称。使用skip_serializing_if搭配Option::is_none。使用default属性设置默认值。

Error Handling

错误处理

thiserror: Derive Error on enum with error attribute for display messages. Use from attribute for automatic conversion from source errors. Implement IntoResponse by matching on variants and returning status code with Json body containing error message.
thiserror:在枚举上派生Error,使用error属性定义显示消息。使用from属性实现从源错误的自动转换。通过匹配变体实现IntoResponse,返回状态码和包含错误消息的Json响应体。

CLI Development: clap

CLI开发:clap

Derive Parser on main Cli struct with command attributes for name, version, about. Use arg attribute for global flags. Derive Subcommand on enum for commands. Match on command in main to dispatch logic.
在主Cli结构体上派生Parser,使用command属性设置名称、版本和描述。使用arg属性定义全局标志。在枚举上派生Subcommand以定义子命令。在主函数中匹配子命令并分发逻辑。

Testing Patterns

测试模式

Create test module with cfg(test) attribute. Define tokio::test async functions. Call setup helpers, invoke functions under test, and use assert! macros for verification.

创建带有cfg(test)属性的测试模块。定义tokio::test异步函数。调用设置辅助函数,调用待测试函数,使用assert!宏进行验证。

Advanced Patterns

高级模式

For comprehensive coverage including:
  • Advanced ownership patterns, lifetimes, and smart pointers
  • Trait design and generic programming
  • Performance optimization strategies and profiling
  • Engineering best practices and coding guidelines
  • Async patterns and concurrency
See: reference/engineering.md for ownership and traits, reference/performance.md for optimization, reference/guidelines.md for coding standards
如需全面了解以下内容:
  • 高级所有权模式、lifetimes与智能指针
  • 特征设计与泛型编程
  • 性能优化策略与性能分析
  • 工程最佳实践与编码规范
  • 异步模式与并发
请参阅:reference/engineering.md(所有权与特征)、reference/performance.md(优化)、reference/guidelines.md(编码标准)

Performance Optimization

性能优化

Release Build: In Cargo.toml profile.release section, enable lto, set codegen-units to 1, set panic to abort, and enable strip.
发布构建:在Cargo.toml的profile.release部分,启用lto,设置codegen-units为1,将panic设置为abort,并启用strip。

Deployment

部署

Minimal Container: Use multi-stage Dockerfile. First stage uses rust alpine image, copies Cargo files, creates dummy main for dependency caching, builds release, copies source, touches main.rs for rebuild, builds final release. Second stage uses alpine, copies binary from builder, exposes port, and sets CMD.
最小容器:使用多阶段Dockerfile。第一阶段使用rust alpine镜像,复制Cargo文件,创建虚拟main函数以缓存依赖,构建发布版本,复制源代码,修改main.rs触发重建,构建最终发布版本。第二阶段使用alpine镜像,从构建阶段复制二进制文件,暴露端口,设置CMD。

Concurrency

并发

Rate-Limited Operations: Create Arc-wrapped Semaphore with max permits. Map over items spawning tasks that acquire permit, process, and return result. Use futures::future::join_all to collect results.

速率限制操作:创建Arc包裹的Semaphore,设置最大许可数。遍历项目并生成任务,任务中获取许可、处理任务并返回结果。使用futures::future::join_all收集结果。

Context7 Integration

Context7集成

Library Documentation Access:
  • /rust-lang/rust
    - Rust language and stdlib
  • /tokio-rs/tokio
    - Tokio async runtime
  • /tokio-rs/axum
    - Axum web framework
  • /launchbadge/sqlx
    - SQLx async SQL
  • /serde-rs/serde
    - Serialization framework
  • /dtolnay/thiserror
    - Error derive
  • /clap-rs/clap
    - CLI parser

库文档访问:
  • /rust-lang/rust
    - Rust语言与标准库
  • /tokio-rs/tokio
    - Tokio异步运行时
  • /tokio-rs/axum
    - Axum Web框架
  • /launchbadge/sqlx
    - SQLx异步SQL库
  • /serde-rs/serde
    - 序列化框架
  • /dtolnay/thiserror
    - 错误派生库
  • /clap-rs/clap
    - CLI解析器

Works Well With

协同工具

  • moai-lang-go
    - Go systems programming patterns
  • moai-domain-backend
    - REST API architecture and microservices patterns
  • moai-foundation-quality
    - Security hardening for Rust applications
  • moai-workflow-testing
    - Test-driven development workflows

  • moai-lang-go
    - Go系统编程模式
  • moai-domain-backend
    - REST API架构与微服务模式
  • moai-foundation-quality
    - Rust应用安全加固
  • moai-workflow-testing
    - 测试驱动开发流程

Troubleshooting

故障排除

Common Issues:
  • Cargo errors: Run cargo clean followed by cargo build
  • Version check: Run rustc --version and cargo --version
  • Dependency issues: Run cargo update and cargo tree
  • Compile-time SQL check: Run cargo sqlx prepare
Performance Characteristics:
  • Startup Time: 50-100ms
  • Memory Usage: 5-20MB base
  • Throughput: 100k-200k req/s
  • Latency: p99 less than 5ms
  • Container Size: 5-15MB (alpine)

常见问题:
  • Cargo错误:运行cargo clean后再执行cargo build
  • 版本检查:运行rustc --version和cargo --version
  • 依赖问题:运行cargo update和cargo tree
  • 编译期SQL检查:运行cargo sqlx prepare
性能指标:
  • 启动时间:50-100ms
  • 内存占用:基础5-20MB
  • 吞吐量:100k-200k请求/秒
  • 延迟:p99小于5ms
  • 容器大小:5-15MB(alpine镜像)

Additional Resources

额外资源

See reference/engineering.md for advanced ownership patterns and trait design.
See reference/performance.md for optimization strategies and profiling techniques.
See reference/guidelines.md for Rust coding standards and best practices.

Last Updated: 2026-01-11 Version: 1.2.0
请参阅reference/engineering.md了解高级所有权模式与特征设计。
请参阅reference/performance.md了解优化策略与性能分析技术。
请参阅reference/guidelines.md了解Rust编码标准与最佳实践。

最后更新:2026-01-11 版本:1.2.0