rust-author
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRust — Authoring & Setup
Rust — 项目编写与搭建
| Concern | Section |
|---|---|
| Idiomatic Rust patterns — ownership, errors, clippy, dispatch | Best Practices |
| Scaffolding new projects — Cargo.toml, workspaces, CI, rustfmt | Project Setup |
If you have an existing project and need to write or refactor code → start at Best Practices.
If you're spinning up a new crate or workspace → start at Project Setup.
For reviewing existing Rust code (source, tests, async, FFI), see .
rust-reviewBest Practices
最佳实践
Rust Best Practices
Rust最佳实践
Guidance for writing idiomatic, performant, and safe Rust code. This is a development skill, not a review skill -- use it when building, not reviewing.
编写符合Rust风格、高性能且安全的代码指南。这是一项开发技能,而非评审技能——适用于代码构建阶段,而非评审阶段。
Quick Reference
快速参考
| Topic | Key Rule | Reference |
|---|---|---|
| Ownership | Borrow by default, clone only when you need a separate owned copy | references/coding-idioms.md |
| Clippy | Run | references/clippy-config.md |
| Performance | Don't guess, measure. Profile with | references/performance.md |
| Generics | Static dispatch by default, dynamic dispatch when you need mixed types | references/generics-dispatch.md |
| Type State | Encode state in the type system when invalid operations should be compile errors | references/type-state-pattern.md |
| Documentation | | references/documentation.md |
| Pointers | Choose pointer types based on ownership needs and threading model | references/pointer-types.md |
| API Design | Unsurprising, flexible, obvious, constrained -- encode invariants in types | references/api-design.md |
| Ecosystem | Evaluate crates, pick error handling strategy, stay current | references/ecosystem-patterns.md |
| 主题 | 核心规则 | 参考文档 |
|---|---|---|
| 所有权 | 默认使用借用,仅在需要独立的自有副本时才克隆 | references/coding-idioms.md |
| Clippy | 每次提交都运行 | references/clippy-config.md |
| 性能 | 不要猜测,要测量。先使用 | references/performance.md |
| 泛型 | 默认使用静态分发,仅在需要混合类型时使用动态分发 | references/generics-dispatch.md |
| 类型状态模式 | 当无效操作应触发编译错误时,将状态编码到类型系统中 | references/type-state-pattern.md |
| 文档 | | references/documentation.md |
| 指针 | 根据所有权需求和线程模型选择指针类型 | references/pointer-types.md |
| API设计 | 直观、灵活、清晰、受限——将不变量编码到类型中 | references/api-design.md |
| 生态系统 | 评估依赖包,选择错误处理策略,保持版本更新 | references/ecosystem-patterns.md |
Coding Idioms
编码规范
Prefer over , use / in parameters, and chain iterators instead of index-based loops. For Option/Result, use for early returns and for propagation. See references/coding-idioms.md for ownership, iterator, and import patterns.
&T.clone()&str&[T]let Ok(x) = expr else { return }?优先使用而非,参数中使用/,使用迭代器链式调用而非基于索引的循环。对于Option/Result,使用提前返回,使用传播错误。有关所有权、迭代器和导入模式,请查看references/coding-idioms.md。
&T.clone()&str&[T]let Ok(x) = expr else { return }?Error Handling
错误处理
Return for fallible operations. Use for library error types, for binaries. Propagate with , never outside tests. See references/coding-idioms.md for Option/Result patterns.
Result<T, E>thiserroranyhow?unwrap()对于可能失败的操作,返回。库类型使用,二进制程序使用。使用传播错误,测试之外绝不使用。有关Option/Result模式,请查看references/coding-idioms.md。
Result<T, E>thiserroranyhow?unwrap()Clippy Discipline
Clippy规范
Run on every commit. Configure workspace lints in and use (not ) as the standard for lint suppression -- it warns when the suppression becomes stale. See references/clippy-config.md for lint configuration and key lints.
cargo clippy --all-targets --all-features -- -D warningsCargo.toml#[expect(clippy::lint)]#[allow]每次提交都运行。在中配置工作区的代码检查规则,使用(而非)作为禁用检查规则的标准方式——当禁用规则变得多余时,它会发出警告。有关检查规则配置和关键规则,请查看references/clippy-config.md。
cargo clippy --all-targets --all-features -- -D warningsCargo.toml#[expect(clippy::lint)]#[allow]Performance Mindset
性能思维
Always benchmark with , profile before optimizing, and avoid cloning in loops or premature calls. Keep small types on the stack and heap-allocate only recursive structures and large buffers. See references/performance.md for profiling tools and allocation guidance.
--release.collect()始终使用模式进行基准测试,优化前先做性能分析,避免在循环中克隆或过早调用。将小型类型放在栈上,仅对递归结构和大型缓冲区进行堆分配。有关性能分析工具和分配指南,请查看references/performance.md。
--release.collect()Generics and Dispatch
泛型与分发
Use static dispatch ( / ) by default for zero-cost monomorphization. Switch to only for heterogeneous collections or plugin architectures, preferring over when ownership isn't needed. In edition 2024, captures all in-scope lifetimes by default -- use for precise capture control. Prefer native in traits over the crate for static dispatch. See references/generics-dispatch.md for dispatch trade-offs, RPIT capture rules, and async trait guidance.
impl Trait<T: Trait>dyn Trait&dyn TraitBox<dyn Trait>-> impl Trait+ use<'a, T>async fnasync-trait默认使用静态分发( / )以实现零成本单态化。仅在处理异构集合或插件架构时切换到,当不需要所有权时,优先使用而非。在2024版本中,默认捕获所有作用域内的生命周期——如需精确控制捕获范围,请使用。优先使用原生在 trait 中实现异步,而非包以实现静态分发。有关分发权衡、RPIT捕获规则和异步trait指南,请查看references/generics-dispatch.md。
impl Trait<T: Trait>dyn Trait&dyn TraitBox<dyn Trait>-> impl Trait+ use<'a, T>async fnasync-traitType State Pattern
类型状态模式
Encode valid states in the type system so invalid operations become compile errors. Use for builders with required fields, protocol state machines, and workflow pipelines. See references/type-state-pattern.md for implementation patterns and when to avoid.
将有效状态编码到类型系统中,使无效操作触发编译错误。适用于带有必填字段的构建器、协议状态机和工作流流水线。有关实现模式和适用场景,请查看references/type-state-pattern.md。
Documentation
文档编写
Use for why, for what/how on public APIs, and for module purpose. Every needs a linked issue and library crates should enable . Use to provide custom compiler errors for your public traits. See references/documentation.md for doc test patterns, comment conventions, and diagnostic attributes.
///////!TODO#![deny(missing_docs)]#[diagnostic::on_unimplemented]使用说明原因,说明公共API的功能与用法,说明模块的用途。每个都需要关联一个问题,库包应启用。使用为你的公共trait提供自定义编译错误。有关文档测试模式、注释规范和诊断属性,请查看references/documentation.md。
///////!TODO#![deny(missing_docs)]#[diagnostic::on_unimplemented]API Design
API设计
Follow four principles: unsurprising (reuse standard names and traits), flexible (use generics and to avoid unnecessary restrictions), obvious (encode invariants in the type system so misuse is a compile error), and constrained (expose only what you can commit to long-term). Use for types that may grow, seal traits you need to extend without breaking changes, and wrap foreign types in newtypes to control your SemVer surface. See references/api-design.md for builder patterns, sealed traits, and SemVer implications.
impl Trait#[non_exhaustive]遵循四个原则:直观(复用标准名称和trait)、灵活(使用泛型和避免不必要的限制)、清晰(将不变量编码到类型系统中,使误用触发编译错误)、受限(仅暴露你能长期维护的内容)。对于可能扩展的类型,使用;对于需要扩展而不破坏兼容性的trait,使用密封trait;将外部类型包装在新类型中以控制你的语义化版本(SemVer)范围。有关构建器模式、密封trait和SemVer影响,请查看references/api-design.md。
impl Trait#[non_exhaustive]Ecosystem Patterns
生态系统模式
Evaluate crates by recent download trends, maintenance activity, documentation quality, and transitive dependency weight. Use for library error types, for binaries, and when you need custom error reporters. Prefer vendoring or writing code yourself when a crate pulls heavy dependencies for a small feature. Run for license and vulnerability auditing and to trim unused dependencies. See references/ecosystem-patterns.md for crate evaluation criteria, edition migration, and essential tooling.
thiserroranyhoweyrecargo-denycargo-udeps根据近期下载趋势、维护活跃度、文档质量和传递依赖权重评估依赖包。库类型使用,二进制程序使用,需要自定义错误报告器时使用。当某个依赖包仅为小功能引入大量依赖时,优先使用 vendoring 或自行编写代码。运行进行许可证和漏洞审计,运行清理未使用的依赖。有关依赖包评估标准、版本迁移和必备工具,请查看references/ecosystem-patterns.md。
thiserroranyhoweyrecargo-denycargo-udepsPointer Types
指针类型
Choose pointer types based on ownership and threading: for single-owner heap allocation, / for shared ownership, /// for interior mutability. Use / (stable since 1.80) instead of or . See references/pointer-types.md for the full single-thread vs multi-thread decision table and migration guidance.
<!-- cross-ref:start -->Box<T>Rc<T>Arc<T>CellRefCellMutexRwLockLazyLockLazyCelllazy_staticonce_cell根据所有权和线程需求选择指针类型:用于单所有者堆分配,/用于共享所有权,///用于内部可变性。使用/(自1.80版本起稳定)替代或。有关单线程与多线程的完整决策表和迁移指南,请查看references/pointer-types.md。
<!-- cross-ref:start -->Box<T>Rc<T>Arc<T>CellRefCellMutexRwLockLazyLockLazyCelllazy_staticonce_cellSee also (related skills — Rust family)
相关技能(Rust系列)
If your issue relates to:
- scaffold a new Rust project — Cargo.toml, workspaces, CI — check if appropriate.
rust-project-setup - review Rust source code — check if appropriate.
rust-code-review - review Rust tests specifically — check if appropriate.
rust-testing-code-review - review tokio async runtime usage, sync primitives, channels — check if appropriate.
tokio-async-code-review - review Rust FFI — type safety, memory layout, unsafe boundaries — check if appropriate.
ffi-code-review
如果你的问题涉及:
- 搭建新Rust项目——Cargo.toml、工作区、CI —— 如有需要,请查看。
rust-project-setup - 评审Rust源码 —— 如有需要,请查看。
rust-code-review - 专门评审Rust测试 —— 如有需要,请查看。
rust-testing-code-review - 评审tokio异步运行时使用、同步原语、通道 —— 如有需要,请查看。
tokio-async-code-review - 评审Rust FFI——类型安全、内存布局、unsafe边界 —— 如有需要,请查看。
ffi-code-review
Project Setup
项目搭建
Rust Project Setup
Rust项目搭建
Step-by-step guidance for setting up new Rust projects with proper configuration, linting, and CI.
为新Rust项目进行正确配置、代码检查和CI设置的分步指南。
Quick Reference
快速参考
| Topic | Reference |
|---|---|
| Cargo.toml configuration, profiles, dependencies | references/cargo-config.md |
| Workspace organization, member layout, shared deps | references/workspace-layout.md |
| GitHub Actions CI, caching, MSRV checks | references/ci-setup.md |
| Feature flags, conditional compilation, build scripts | references/features-conditional.md |
| no_std development, embedded targets, cross-compilation | references/no-std.md |
| 主题 | 参考文档 |
|---|---|
| Cargo.toml配置、编译配置文件、依赖 | references/cargo-config.md |
| 工作区组织、成员布局、共享依赖 | references/workspace-layout.md |
| GitHub Actions CI、缓存、MSRV检查 | references/ci-setup.md |
| 功能标志、条件编译、构建脚本 | references/features-conditional.md |
| no_std开发、嵌入式目标、交叉编译 | references/no-std.md |
New Project Checklist
新项目检查清单
1. Create the Project
1. 创建项目
shell
undefinedshell
undefinedBinary
二进制程序
cargo init my-app
cargo init my-app
Library
库
cargo init --lib my-lib
cargo init --lib my-lib
Workspace (create Cargo.toml manually)
工作区(手动创建Cargo.toml)
mkdir my-workspace && cd my-workspace
undefinedmkdir my-workspace && cd my-workspace
undefined2. Configure Cargo.toml
2. 配置Cargo.toml
Set edition, rust-version (MSRV), and metadata:
toml
[package]
name = "my-app"
version = "0.1.0"
edition = "2024"
rust-version = "1.85"设置版本、rust-version(最低支持Rust版本,MSRV)和元数据:
toml
[package]
name = "my-app"
version = "0.1.0"
edition = "2024"
rust-version = "1.85"3. Set Up Linting
3. 设置代码检查
Add clippy and rustfmt configuration:
toml
undefined添加clippy和rustfmt配置:
toml
undefinedCargo.toml
Cargo.toml
[lints.clippy]
all = { level = "deny", priority = 10 }
pedantic = { level = "warn", priority = 3 }
[lints.rust]
future-incompatible = "warn"
nonstandard_style = "deny"
[lints.clippy]
all = { level = "deny", priority = 10 }
pedantic = { level = "warn", priority = 3 }
[lints.rust]
future-incompatible = "warn"
nonstandard_style = "deny"
unsafe_op_in_unsafe_fn is deny-by-default in edition 2024 — no need to set it
unsafe_op_in_unsafe_fn在2024版本中默认deny——无需设置
> **Edition 2024 lint defaults**: `unsafe_op_in_unsafe_fn` is deny by default. Unsafe operations inside `unsafe fn` require explicit `unsafe {}` blocks. The `gen` keyword is reserved — use `r#gen` if needed as an identifier.
```toml
> **2024版本检查规则默认值**:`unsafe_op_in_unsafe_fn`默认deny。`unsafe fn`内部的不安全操作需要显式的`unsafe {}`块。`gen`是保留关键字——如需将其用作标识符,请使用`r#gen`。
```tomlrustfmt.toml
rustfmt.toml
edition = "2024"
reorder_imports = true
imports_granularity = "Crate"
group_imports = "StdExternalCrate"
undefinededition = "2024"
reorder_imports = true
imports_granularity = "Crate"
group_imports = "StdExternalCrate"
undefined4. Configure Profiles
4. 配置编译配置文件
toml
[profile.release]
lto = true
codegen-units = 1
strip = truetoml
[profile.release]
lto = true
codegen-units = 1
strip = true5. Set Up CI
5. 设置CI
Add GitHub Actions workflow for check, clippy, test, and fmt. See references/ci-setup.md.
添加GitHub Actions工作流,用于检查、clippy、测试和格式化。请查看references/ci-setup.md。
6. Cargo.lock Policy
6. Cargo.lock策略
- Binaries: Commit (reproducible builds)
Cargo.lock - Libraries: Do NOT commit (consumers resolve their own versions)
Cargo.lock - Add to for libraries:
.gitignoreCargo.lock
- 二进制程序:提交(可复现构建)
Cargo.lock - 库:不要提交(使用者自行解析版本)
Cargo.lock - 对于库,将添加到
Cargo.lock.gitignore
7. Documentation Setup
7. 文档设置
For library crates, enable doc lints:
rust
// src/lib.rs
#![deny(missing_docs)]Prefer over for temporary suppressions — it warns when the suppression becomes unnecessary:
#[expect(lint)]#[allow(lint)]rust
#[expect(dead_code, reason = "used in next PR")]
fn upcoming_feature() {}对于库包,启用文档检查规则:
rust
// src/lib.rs
#![deny(missing_docs)]临时禁用检查规则时,优先使用而非——当禁用规则变得多余时,它会发出警告:
#[expect(lint)]#[allow(lint)]rust
#[expect(dead_code, reason = "将在下一个PR中使用")]
fn upcoming_feature() {}Workspace vs Single Crate
工作区 vs 单包
| Use | When |
|---|---|
| Single crate | Small project, CLI tool, simple library |
| Workspace | Multiple related crates, shared dependencies, separate compile targets |
Workspaces reduce compile times by sharing dependencies and build artifacts across members.
| 使用场景 | 适用时机 |
|---|---|
| 单包 | 小型项目、CLI工具、简单库 |
| 工作区 | 多个相关包、共享依赖、独立编译目标 |
工作区通过在成员之间共享依赖和构建产物来减少编译时间。
Project Structure
项目结构
Binary
二进制程序
text
my-app/
Cargo.toml
rustfmt.toml
src/
main.rs
lib.rs # separate logic from entry point
tests/
integration_test.rstext
my-app/
Cargo.toml
rustfmt.toml
src/
main.rs
lib.rs # 将逻辑与入口点分离
tests/
integration_test.rsLibrary
库
text
my-lib/
Cargo.toml
rustfmt.toml
src/
lib.rs
module_a.rs
module_b/
mod.rs
types.rs
tests/
api_test.rs
examples/
basic_usage.rstext
my-lib/
Cargo.toml
rustfmt.toml
src/
lib.rs
module_a.rs
module_b/
mod.rs
types.rs
tests/
api_test.rs
examples/
basic_usage.rsWorkspace
工作区
text
my-workspace/
Cargo.toml # [workspace] definition
rustfmt.toml # shared formatting
crates/
core/ # shared types and logic
api/ # HTTP server
cli/ # command-line interfacetext
my-workspace/
Cargo.toml # [workspace]定义
rustfmt.toml # 共享格式化配置
crates/
core/ # 共享类型与逻辑
api/ # HTTP服务器
cli/ # 命令行界面Dependency Best Practices
依赖最佳实践
- Pin exact versions for binaries:
serde = "=1.0.210" - Use version ranges for libraries:
serde = "1" - Group features explicitly:
tokio = { version = "1", features = ["rt-multi-thread", "macros"] } - Use for test-only crates
[dev-dependencies] - Review for duplicate versions
cargo tree - Run for security vulnerabilities
cargo audit - Replace /
once_cellwithlazy_static(stable since Rust 1.80)std::sync::LazyLock
- 二进制程序固定精确版本:
serde = "=1.0.210" - 库使用版本范围:
serde = "1" - 显式分组功能:
tokio = { version = "1", features = ["rt-multi-thread", "macros"] } - 使用仅用于测试的依赖包
[dev-dependencies] - 查看检查重复版本
cargo tree - 运行检查安全漏洞
cargo audit - 使用替代
std::sync::LazyLock/once_cell(自Rust 1.80版本起稳定)lazy_static
Edition 2024 Migration Notes
2024版本迁移说明
When migrating existing projects to edition 2024:
- bodies now require explicit
unsafe fnblocks around unsafe operationsunsafe {} - blocks must be written as
extern "C" {}unsafe extern "C" {} - and
#[no_mangle]require#[export_name]and#[unsafe(no_mangle)]#[unsafe(export_name)] - is a reserved keyword — rename any
genidentifiers togenor choose a different namer#gen - captures all in-scope lifetimes by default; use
-> impl Traitfor precise control+ use<'a> - (never type) falls back to
!instead of!— review match arms and diverging expressions() - Temporaries in and tail expressions drop earlier — review code holding locks or guards in these positions
if let
Run to auto-fix most mechanical changes.
cargo fix --edition将现有项目迁移到2024版本时:
- 体现在需要在不安全操作周围添加显式的
unsafe fn块unsafe {} - 块必须写成
extern "C" {}unsafe extern "C" {} - 和
#[no_mangle]需要改为#[export_name]和#[unsafe(no_mangle)]#[unsafe(export_name)] - 是保留关键字——将所有
gen标识符重命名为gen或选择其他名称r#gen - 默认捕获所有作用域内的生命周期;如需精确控制,请使用
-> impl Trait+ use<'a> - (never类型)现在回退为
!而非!——检查匹配分支和发散表达式() - 和尾表达式中的临时值会更早被释放——检查在这些位置持有锁或守卫的代码
if let
运行自动修复大多数机械性变更。
cargo fix --editionRelated Skills
相关技能
- — idiomatic patterns and edition 2024 coding guidance
beagle-rust:rust-best-practices - — code review covering ownership, unsafe, and trait design
beagle-rust:rust-code-review
- —— 符合Rust风格的模式和2024版本编码指南
beagle-rust:rust-best-practices - —— 涵盖所有权、unsafe和trait设计的代码评审
beagle-rust:rust-code-review
See also (related skills — Rust family)
相关技能(Rust系列)
If your issue relates to:
- idiomatic Rust — ownership, errors, clippy, dispatch — check if appropriate.
rust-best-practices - review Rust source code — check if appropriate.
rust-code-review - review Rust tests specifically — check if appropriate.
rust-testing-code-review - review tokio async runtime usage, sync primitives, channels — check if appropriate.
tokio-async-code-review - review Rust FFI — type safety, memory layout, unsafe boundaries — check if appropriate.
ffi-code-review
如果你的问题涉及:
- 符合Rust风格的写法——所有权、错误处理、clippy、分发 —— 如有需要,请查看。
rust-best-practices - 评审Rust源码 —— 如有需要,请查看。
rust-code-review - 专门评审Rust测试 —— 如有需要,请查看。
rust-testing-code-review - 评审tokio异步运行时使用、同步原语、通道 —— 如有需要,请查看。
tokio-async-code-review - 评审Rust FFI——类型安全、内存布局、unsafe边界 —— 如有需要,请查看。
ffi-code-review