rust-author

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rust — Authoring & Setup

Rust — 项目编写与搭建

ConcernSection
Idiomatic Rust patterns — ownership, errors, clippy, dispatchBest Practices
Scaffolding new projects — Cargo.toml, workspaces, CI, rustfmtProject 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-review
.

关注点章节
符合Rust风格的代码模式——所有权、错误处理、clippy、分发最佳实践
新项目脚手架搭建——Cargo.toml、工作区、CI、rustfmt项目搭建
如果你已有一个项目,需要编写或重构代码 → 从最佳实践开始。 如果你要创建一个新包或工作区 → 从项目搭建开始。
如需评审现有Rust代码(源码、测试、异步、FFI),请查看
rust-review

Best 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

快速参考

TopicKey RuleReference
OwnershipBorrow by default, clone only when you need a separate owned copyreferences/coding-idioms.md
ClippyRun
cargo clippy -- -D warnings
on every commit; configure workspace lints
references/clippy-config.md
PerformanceDon't guess, measure. Profile with
--release
first
references/performance.md
GenericsStatic dispatch by default, dynamic dispatch when you need mixed typesreferences/generics-dispatch.md
Type StateEncode state in the type system when invalid operations should be compile errorsreferences/type-state-pattern.md
Documentation
//
for why,
///
for what and how,
//!
for module/crate purpose
references/documentation.md
PointersChoose pointer types based on ownership needs and threading modelreferences/pointer-types.md
API DesignUnsurprising, flexible, obvious, constrained -- encode invariants in typesreferences/api-design.md
EcosystemEvaluate crates, pick error handling strategy, stay currentreferences/ecosystem-patterns.md
主题核心规则参考文档
所有权默认使用借用,仅在需要独立的自有副本时才克隆references/coding-idioms.md
Clippy每次提交都运行
cargo clippy -- -D warnings
;配置工作区的代码检查规则
references/clippy-config.md
性能不要猜测,要测量。先使用
--release
模式进行性能分析
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
&T
over
.clone()
, use
&str
/
&[T]
in parameters, and chain iterators instead of index-based loops. For Option/Result, use
let Ok(x) = expr else { return }
for early returns and
?
for propagation. See references/coding-idioms.md for ownership, iterator, and import patterns.
优先使用
&T
而非
.clone()
,参数中使用
&str
/
&[T]
,使用迭代器链式调用而非基于索引的循环。对于Option/Result,使用
let Ok(x) = expr else { return }
提前返回,使用
?
传播错误。有关所有权、迭代器和导入模式,请查看references/coding-idioms.md

Error Handling

错误处理

Return
Result<T, E>
for fallible operations. Use
thiserror
for library error types,
anyhow
for binaries. Propagate with
?
, never
unwrap()
outside tests. See references/coding-idioms.md for Option/Result patterns.
对于可能失败的操作,返回
Result<T, E>
。库类型使用
thiserror
,二进制程序使用
anyhow
。使用
?
传播错误,测试之外绝不使用
unwrap()
。有关Option/Result模式,请查看references/coding-idioms.md

Clippy Discipline

Clippy规范

Run
cargo clippy --all-targets --all-features -- -D warnings
on every commit. Configure workspace lints in
Cargo.toml
and use
#[expect(clippy::lint)]
(not
#[allow]
) 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 warnings
。在
Cargo.toml
中配置工作区的代码检查规则,使用
#[expect(clippy::lint)]
(而非
#[allow]
)作为禁用检查规则的标准方式——当禁用规则变得多余时,它会发出警告。有关检查规则配置和关键规则,请查看references/clippy-config.md

Performance Mindset

性能思维

Always benchmark with
--release
, profile before optimizing, and avoid cloning in loops or premature
.collect()
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

Generics and Dispatch

泛型与分发

Use static dispatch (
impl Trait
/
<T: Trait>
) by default for zero-cost monomorphization. Switch to
dyn Trait
only for heterogeneous collections or plugin architectures, preferring
&dyn Trait
over
Box<dyn Trait>
when ownership isn't needed. In edition 2024,
-> impl Trait
captures all in-scope lifetimes by default -- use
+ use<'a, T>
for precise capture control. Prefer native
async fn
in traits over the
async-trait
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 Trait
而非
Box<dyn Trait>
。在2024版本中,
-> impl Trait
默认捕获所有作用域内的生命周期——如需精确控制捕获范围,请使用
+ use<'a, T>
。优先使用原生
async fn
在 trait 中实现异步,而非
async-trait
包以实现静态分发。有关分发权衡、RPIT捕获规则和异步trait指南,请查看references/generics-dispatch.md

Type 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
TODO
needs a linked issue and library crates should enable
#![deny(missing_docs)]
. Use
#[diagnostic::on_unimplemented]
to provide custom compiler errors for your public traits. See references/documentation.md for doc test patterns, comment conventions, and diagnostic attributes.
使用
//
说明原因,
///
说明公共API的功能与用法,
//!
说明模块的用途。每个
TODO
都需要关联一个问题,库包应启用
#![deny(missing_docs)]
。使用
#[diagnostic::on_unimplemented]
为你的公共trait提供自定义编译错误。有关文档测试模式、注释规范和诊断属性,请查看references/documentation.md

API Design

API设计

Follow four principles: unsurprising (reuse standard names and traits), flexible (use generics and
impl Trait
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
#[non_exhaustive]
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.
遵循四个原则:直观(复用标准名称和trait)、灵活(使用泛型和
impl Trait
避免不必要的限制)、清晰(将不变量编码到类型系统中,使误用触发编译错误)、受限(仅暴露你能长期维护的内容)。对于可能扩展的类型,使用
#[non_exhaustive]
;对于需要扩展而不破坏兼容性的trait,使用密封trait;将外部类型包装在新类型中以控制你的语义化版本(SemVer)范围。有关构建器模式、密封trait和SemVer影响,请查看references/api-design.md

Ecosystem Patterns

生态系统模式

Evaluate crates by recent download trends, maintenance activity, documentation quality, and transitive dependency weight. Use
thiserror
for library error types,
anyhow
for binaries, and
eyre
when you need custom error reporters. Prefer vendoring or writing code yourself when a crate pulls heavy dependencies for a small feature. Run
cargo-deny
for license and vulnerability auditing and
cargo-udeps
to trim unused dependencies. See references/ecosystem-patterns.md for crate evaluation criteria, edition migration, and essential tooling.
根据近期下载趋势、维护活跃度、文档质量和传递依赖权重评估依赖包。库类型使用
thiserror
,二进制程序使用
anyhow
,需要自定义错误报告器时使用
eyre
。当某个依赖包仅为小功能引入大量依赖时,优先使用 vendoring 或自行编写代码。运行
cargo-deny
进行许可证和漏洞审计,运行
cargo-udeps
清理未使用的依赖。有关依赖包评估标准、版本迁移和必备工具,请查看references/ecosystem-patterns.md

Pointer Types

指针类型

Choose pointer types based on ownership and threading:
Box<T>
for single-owner heap allocation,
Rc<T>
/
Arc<T>
for shared ownership,
Cell
/
RefCell
/
Mutex
/
RwLock
for interior mutability. Use
LazyLock
/
LazyCell
(stable since 1.80) instead of
lazy_static
or
once_cell
. 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>
用于共享所有权,
Cell
/
RefCell
/
Mutex
/
RwLock
用于内部可变性。使用
LazyLock
/
LazyCell
(自1.80版本起稳定)替代
lazy_static
once_cell
。有关单线程与多线程的完整决策表和迁移指南,请查看references/pointer-types.md
<!-- cross-ref:start -->

See also (related skills — Rust family)

相关技能(Rust系列)

If your issue relates to:
  • scaffold a new Rust project — Cargo.toml, workspaces, CI — check
    rust-project-setup
    if appropriate.
  • review Rust source code — check
    rust-code-review
    if appropriate.
  • review Rust tests specifically — check
    rust-testing-code-review
    if appropriate.
  • review tokio async runtime usage, sync primitives, channels — check
    tokio-async-code-review
    if appropriate.
  • review Rust FFI — type safety, memory layout, unsafe boundaries — check
    ffi-code-review
    if appropriate.
<!-- cross-ref:end -->
如果你的问题涉及:
  • 搭建新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
<!-- cross-ref:end -->

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

快速参考

TopicReference
Cargo.toml configuration, profiles, dependenciesreferences/cargo-config.md
Workspace organization, member layout, shared depsreferences/workspace-layout.md
GitHub Actions CI, caching, MSRV checksreferences/ci-setup.md
Feature flags, conditional compilation, build scriptsreferences/features-conditional.md
no_std development, embedded targets, cross-compilationreferences/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
undefined
shell
undefined

Binary

二进制程序

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
undefined
mkdir my-workspace && cd my-workspace
undefined

2. 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
undefined

Cargo.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`。

```toml

rustfmt.toml

rustfmt.toml

edition = "2024" reorder_imports = true imports_granularity = "Crate" group_imports = "StdExternalCrate"
undefined
edition = "2024" reorder_imports = true imports_granularity = "Crate" group_imports = "StdExternalCrate"
undefined

4. Configure Profiles

4. 配置编译配置文件

toml
[profile.release]
lto = true
codegen-units = 1
strip = true
toml
[profile.release]
lto = true
codegen-units = 1
strip = true

5. 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
    Cargo.lock
    (reproducible builds)
  • Libraries: Do NOT commit
    Cargo.lock
    (consumers resolve their own versions)
  • Add to
    .gitignore
    for libraries:
    Cargo.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
#[expect(lint)]
over
#[allow(lint)]
for temporary suppressions — it warns when the suppression becomes unnecessary:
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 单包

UseWhen
Single crateSmall project, CLI tool, simple library
WorkspaceMultiple 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.rs
text
my-app/
  Cargo.toml
  rustfmt.toml
  src/
    main.rs
    lib.rs      # 将逻辑与入口点分离
  tests/
    integration_test.rs

Library

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.rs
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.rs

Workspace

工作区

text
my-workspace/
  Cargo.toml          # [workspace] definition
  rustfmt.toml        # shared formatting
  crates/
    core/             # shared types and logic
    api/              # HTTP server
    cli/              # command-line interface
text
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
    [dev-dependencies]
    for test-only crates
  • Review
    cargo tree
    for duplicate versions
  • Run
    cargo audit
    for security vulnerabilities
  • Replace
    once_cell
    /
    lazy_static
    with
    std::sync::LazyLock
    (stable since Rust 1.80)
  • 二进制程序固定精确版本:
    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
    /
    lazy_static
    (自Rust 1.80版本起稳定)

Edition 2024 Migration Notes

2024版本迁移说明

When migrating existing projects to edition 2024:
  • unsafe fn
    bodies now require explicit
    unsafe {}
    blocks around unsafe operations
  • extern "C" {}
    blocks must be written as
    unsafe extern "C" {}
  • #[no_mangle]
    and
    #[export_name]
    require
    #[unsafe(no_mangle)]
    and
    #[unsafe(export_name)]
  • gen
    is a reserved keyword — rename any
    gen
    identifiers to
    r#gen
    or choose a different name
  • -> impl Trait
    captures all in-scope lifetimes by default; use
    + use<'a>
    for precise control
  • !
    (never type) falls back to
    !
    instead of
    ()
    — review match arms and diverging expressions
  • Temporaries in
    if let
    and tail expressions drop earlier — review code holding locks or guards in these positions
Run
cargo fix --edition
to auto-fix most mechanical changes.
将现有项目迁移到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 --edition
自动修复大多数机械性变更。

Related Skills

相关技能

  • beagle-rust:rust-best-practices
    — idiomatic patterns and edition 2024 coding guidance
  • beagle-rust:rust-code-review
    — code review covering ownership, unsafe, and trait design
<!-- cross-ref:start -->
  • beagle-rust:rust-best-practices
    —— 符合Rust风格的模式和2024版本编码指南
  • beagle-rust:rust-code-review
    —— 涵盖所有权、unsafe和trait设计的代码评审
<!-- cross-ref:start -->

See also (related skills — Rust family)

相关技能(Rust系列)

If your issue relates to:
  • idiomatic Rust — ownership, errors, clippy, dispatch — check
    rust-best-practices
    if appropriate.
  • review Rust source code — check
    rust-code-review
    if appropriate.
  • review Rust tests specifically — check
    rust-testing-code-review
    if appropriate.
  • review tokio async runtime usage, sync primitives, channels — check
    tokio-async-code-review
    if appropriate.
  • review Rust FFI — type safety, memory layout, unsafe boundaries — check
    ffi-code-review
    if appropriate.
<!-- cross-ref:end -->
如果你的问题涉及:
  • 符合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
<!-- cross-ref:end -->