google-rust-style

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Google Rust style

Google Rust 风格

Source: Google Rust Style Guide, read 2026-10-22 at gh-pages
2ac1584
. Section links below use
G#anchor
, short for
https://google.github.io/styleguide/rustguide.html#anchor
.
This skill holds only what Google adds on top of common Rust advice (borrow before you clone,
thiserror
for library errors,
cargo clippy
clean). Pair it with a general Rust skill for the basics. Where common advice disagrees with Google, Google wins (see Overrides).
Out of scope: rules tagged Chrome, Fuchsia or Android (small crates, flat
rust_library
layout,
chromium::import!
, no
async
, no
std::thread
,
fuchsia_sync::Mutex
, per-codebase test frameworks).
来源:Google Rust Style Guide,读取日期为 2026-10-22,对应 gh-pages
2ac1584
。下文中的章节链接使用
G#anchor
,它是
https://google.github.io/styleguide/rustguide.html#anchor
的简写。
本 skill 仅收录 Google 在通用 Rust 建议(优先借用而非克隆、库错误使用
thiserror
、通过
cargo clippy
检查)之外补充的内容。基础知识应搭配通用 Rust skill 使用。通用建议与 Google 指南冲突时,以 Google 指南为准(见覆盖规则)。
不适用范围:标记为 Chrome、Fuchsia 或 Android 的规则(小型 crate、扁平
rust_library
布局、
chromium::import!
、不允许
async
、不允许
std::thread
、
fuchsia_sync::Mutex
、按代码库划分的测试框架)。

Library or application

库还是应用

First decide which kind of crate you are in (G#api-design-context):
  • Library: used by other projects and solves a general problem. Every API rule here binds.
  • Application: one app and one specific problem. API rules are strong recommendations, and simplicity and directness win over reuse.
Rules below marked library follow this split. Every other rule binds both kinds: an application with no outside users still takes the full rustfmt and clippy config except the library block, and every layout, import, error, naming and unsafe rule.
首先确定当前 crate 属于哪一类(G#api-design-context):
  • 库(Library):供其他项目使用并解决通用问题。此处每一条 API 规则都强制适用。
  • 应用(Application):只服务于一个应用和一个特定问题。API 规则属于强烈建议,应优先保证简单、直接,而非追求复用。
下方标有 library 的规则遵循这一区分。其他所有规则同时适用于两类:即使应用没有外部用户,除 library 专属配置块外,仍须采用完整的 rustfmt 和 clippy 配置,并遵守所有布局、导入、错误、命名和 unsafe 规则。

1. Tool config

1. 工具配置

Run
cargo clippy --all-targets --all-features -- -D warnings
in CI so every
warn
below fails the build.
rustfmt.toml
. All three options need nightly rustfmt. Stable 1.98 prints "unstable features are only available in nightly" and ignores them, and the guide lets a stable-only codebase skip them.
max_width = 100
is already rustfmt's default, so it is not set.
toml
imports_granularity = "Module"
hex_literal_case = "Lower"
format_macro_matchers = true
clippy.toml
.
avoid-breaking-exported-api = false
is load-bearing. Without it,
wrong_self_convention
and
ref_option
skip
pub
items, which are exactly the items Google's rules target.
toml
avoid-breaking-exported-api = false
allow-unwrap-in-tests = true
disallowed-methods = [
  { path = "std::panic::catch_unwind", reason = "Google Rust style forbids catch_unwind in first-party code" },
  { path = "std::sync::PoisonError::into_inner", reason = "Google Rust style: never reach inside a poisoned mutex" },
  { path = "std::sync::PoisonError::get_ref", reason = "Google Rust style: never reach inside a poisoned mutex" },
  { path = "std::sync::PoisonError::get_mut", reason = "Google Rust style: never reach inside a poisoned mutex" },
]
Cargo.toml
, every crate. Drop
unsafe_code = "forbid"
only in the one crate that isolates unsafe code.
toml
[lints.rust]
unsafe_code = "forbid"
unstable_features = "deny"

[lints.clippy]
ref_option = "deny"
unwrap_used = "deny"
wildcard_imports = "deny"
needless_for_each = "deny"
undocumented_unsafe_blocks = "deny"
derive_partial_eq_without_eq = "allow"
missing_const_for_fn = "allow"
Library crates merge these keys into the same two tables.
toml
[lints.rust]
missing_docs = "warn"

[lints.clippy]
exhaustive_enums = "deny"
exhaustive_structs = "deny"
must_use_candidate = "deny"
return_self_not_must_use = "deny"
missing_panics_doc = "deny"
To take a guide-sanctioned exception, write
#[expect(<lint>, reason = "...")]
on the item. The
reason
carries the why, so the item needs no comment.
SettingGoogle ruleSection
imports_granularity = "Module"
A
use
imports from one module; no
::
inside
{}
G#use-statement
hex_literal_case
,
format_macro_matchers
Lowercase hex literals; formatted macro matchersG#formatting-other
wildcard_imports
No glob imports. It already exempts Google's allowed cases:
use super::*
in tests,
use Enum::*
inside a function,
pub use sub::*
G#glob-imports
ref_option
, plus default
borrowed_box
and
ptr_arg
Take
&T
,
&[T]
,
&str
,
Option<&T>
, not
&Box<T>
,
&Vec<T>
,
&String
,
&Option<T>
G#flexible-references
default
should_implement_trait
impl FromStr
rather than an inherent
from_str
G#known-traits
default
derivable_impls
Derive when a derive can express itG#derive
default
new_without_default
A type with
new()
implements
Default
G#important-traits
derive_partial_eq_without_eq = "allow"
Prefer
PartialEq
over
Eq
unless you mean reflexivity. The nursery lint pushes the other way
G#important-traits
default
wrong_self_convention
as_
,
to_
,
into_
take the matching
self
G#naming-methods
default
len_without_is_empty
len()
comes with
is_empty()
G#expected-api-sets
disallowed-methods
catch_unwind
catch_unwind
is prohibited. The defense-in-depth entry-point wrapper takes an
#[expect]
G#catch-unwind
disallowed-methods
PoisonError
Never reach inside a poisoned mutexG#poison
exhaustive_enums
,
exhaustive_structs
Public enums and all-pub-field structs used by other teams are
#[non_exhaustive]
G#non-exhaustive-enums, G#non-exhaustive-structs
must_use_candidate
,
return_self_not_must_use
#[must_use]
on pure functions and on types whose value must be consumed
G#must-use-on-functions, G#must-use-on-types
default
unnecessary_unwrap
Pattern-match instead of check-then-unwrapG#dont-check-then-unwrap
unwrap_used
,
allow-unwrap-in-tests
expect
over
unwrap
; tests may panic
G#expect-over-unwrap
needless_for_each
A
for
loop over
Iterator::for_each
G#combinator-chains
unsafe_code
,
undocumented_unsafe_blocks
, default
missing_safety_doc
Unsafe code is isolated in one crate, each block carries
// SAFETY:
, and unsafe fns document their invariants
G#unsafe, G#writing-doc
missing_docs
,
missing_panics_doc
Document public APIs and every panic on malformed inputG#writing-doc
unstable_features
No
#![feature]
. On stable it is already a hard error; the lint covers nightly builds
G#unstable-features
missing_const_for_fn = "allow"
A public fn is
const
only if it will stay
const
. The nursery lint pushes the other way
G#const-functions
在 CI 中运行
cargo clippy --all-targets --all-features -- -D warnings
,使下文中的每个
warn
都会导致构建失败。
rustfmt.toml
。三个选项都需要 nightly rustfmt。Stable 1.98 会输出
"unstable features are only available in nightly"
并忽略这些选项;指南允许仅使用 stable 的代码库跳过它们。
max_width = 100
已是 rustfmt 的默认值,因此不设置。
toml
imports_granularity = "Module"
hex_literal_case = "Lower"
format_macro_matchers = true
clippy.toml
。
avoid-breaking-exported-api = false
是关键配置。如果不设置,
wrong_self_convention
和
ref_option
会跳过
pub
项,而这些恰恰是 Google 规则所针对的对象。
toml
avoid-breaking-exported-api = false
allow-unwrap-in-tests = true
disallowed-methods = [
  { path = "std::panic::catch_unwind", reason = "Google Rust style forbids catch_unwind in first-party code" },
  { path = "std::sync::PoisonError::into_inner", reason = "Google Rust style: never reach inside a poisoned mutex" },
  { path = "std::sync::PoisonError::get_ref", reason = "Google Rust style: never reach inside a poisoned mutex" },
  { path = "std::sync::PoisonError::get_mut", reason = "Google Rust style: never reach inside a poisoned mutex" },
]
Cargo.toml
,每个 crate 都要配置。仅在隔离 unsafe 代码的那一个 crate 中移除
unsafe_code = "forbid"
。
toml
[lints.rust]
unsafe_code = "forbid"
unstable_features = "deny"

[lints.clippy]
ref_option = "deny"
unwrap_used = "deny"
wildcard_imports = "deny"
needless_for_each = "deny"
undocumented_unsafe_blocks = "deny"
derive_partial_eq_without_eq = "allow"
missing_const_for_fn = "allow"
库 crate 应将下列键合并到同样的两个表中。
toml
[lints.rust]
missing_docs = "warn"

[lints.clippy]
exhaustive_enums = "deny"
exhaustive_structs = "deny"
must_use_candidate = "deny"
return_self_not_must_use = "deny"
missing_panics_doc = "deny"
若要采用指南允许的例外,应在相关项上写
#[expect(<lint>, reason = "...")]
。
reason
应说明原因,因此该项无需额外注释。
配置Google 规则章节
imports_granularity = "Module"
每个
use
仅从一个模块导入;
{}
内不使用
::
G#use-statement
hex_literal_case
、
format_macro_matchers
十六进制字面量使用小写;格式化宏匹配器G#formatting-other
wildcard_imports
禁止 glob import。该 lint 已豁免 Google 允许的用例:测试中的
use super::*
、函数内部的
use Enum::*
、
pub use sub::*
G#glob-imports
ref_option
,以及默认的
borrowed_box
和
ptr_arg
使用
&T
、
&[T]
、
&str
、
Option<&T>
,而不是
&Box<T>
、
&Vec<T>
、
&String
、
&Option<T>
G#flexible-references
默认的
should_implement_trait
实现
impl FromStr
,而不是固有方法
from_str
G#known-traits
默认的
derivable_impls
当 derive 能够表达时,使用 deriveG#derive
默认的
new_without_default
具有
new()
的类型应实现
Default
G#important-traits
derive_partial_eq_without_eq = "allow"
除非确实需要自反性,否则优先使用
PartialEq
而非
Eq
。nursery lint 的建议方向相反
G#important-traits
默认的
wrong_self_convention
as_
、
to_
、
into_
接收与名称匹配的
self
G#naming-methods
默认的
len_without_is_empty
提供
len()
时也应提供
is_empty()
G#expected-api-sets
disallowed-methods
中的
catch_unwind
禁止使用
catch_unwind
。纵深防御入口包装器应使用
#[expect]
G#catch-unwind
disallowed-methods
中的
PoisonError
绝不能访问 poisoned mutex 内部G#poison
exhaustive_enums
、
exhaustive_structs
供其他团队使用的公共 enum 和所有字段均为
pub
的 struct 应标记为
#[non_exhaustive]
G#non-exhaustive-enums、G#non-exhaustive-structs
must_use_candidate
、
return_self_not_must_use
纯函数以及值必须被消费的类型应使用
#[must_use]
G#must-use-on-functions、G#must-use-on-types
默认的
unnecessary_unwrap
使用模式匹配,而不是先检查再 unwrapG#dont-check-then-unwrap
unwrap_used
、
allow-unwrap-in-tests
优先使用
expect
而非
unwrap
;测试可以 panic
G#expect-over-unwrap
needless_for_each
对
Iterator::for_each
使用
for
循环
G#combinator-chains
unsafe_code
、
undocumented_unsafe_blocks
,以及默认的
missing_safety_doc
unsafe 代码应隔离在一个 crate 中,每个代码块都应带有
// SAFETY:
,unsafe fn 应记录其不变量
G#unsafe、G#writing-doc
missing_docs
、
missing_panics_doc
为公共 API 以及因输入格式错误而发生的每次 panic 编写文档G#writing-doc
unstable_features
不使用
#![feature]
。在 stable 上它已经是硬错误;该 lint 用于覆盖 nightly 构建
G#unstable-features
missing_const_for_fn = "allow"
只有未来能够持续保持
const
的公共 fn 才应声明为
const
。nursery lint 的建议方向相反
G#const-functions

2. Judgement rules

2. 判断规则

No tool can check these.
non_exhaustive_omitted_patterns
is the lint the guide names for the matching rule, but it is unknown on stable 1.98 and needs a nightly feature, which would break the no-unstable-features rule. That rule stays here as prose.
Modules and imports
  • A leaf module with one primary item
    Foo
    is
    mod foo
    in
    foo.rs
    . G#userdefined-item
  • Non-leaf modules hold only
    mod
    declarations and re-exports, plus at most a little glue code. A
    mod tests
    or
    #[cxx::bridge]
    child still counts as a leaf module. G#non-leaf-modules
  • Define no preludes. Using a third-party prelude is the reviewer's call. G#glob-imports
  • Import a trait inside the function body that uses it, unless the whole file uses it. G#prefer-local-trait-imports
  • Call free functions through their module:
    use std::mem;
    then
    mem::swap(..)
    . Calling a name directly is fine when the name is already unambiguous (C++ interop) or the module name collides. G#toplevel-functions
  • Name types unqualified:
    use regex::Regex;
    then
    Regex
    . Use the module path (
    io::Error
    ) or a rename (
    IoError
    ) for an ambiguous name, a large type family (rustc's
    hir
    ), macros and generated code, and huge import lists. G#type-names
Formatting
  • #[rustfmt::skip]
    is for hand alignment (matrices, rows of similar lines) and generated code only. Personal taste is not a reason. G#formatting-optout
  • Write invisible characters in literals as escapes, such as
    \u{200D}
    . Clippy 0.1.98 does not flag a raw zero-width joiner. G#formatting-other
Ownership and signatures
  • Model ownership as unique owners plus borrows. Reach for
    Rc
    /
    Arc
    only when that structure becomes unreasonably complex, and make the case in review. G#avoid-rc-arc
  • Library: return an iterator (
    impl Iterator
    or a concrete type) instead of a
    Vec<T>
    . Return the
    Vec
    when most callers need one, the implementation naturally builds one, the result will be indexed, the function exists to build a collection, or it hands back an existing vector. Application: a
    Vec
    is fine. G#return-iterators
  • Library: take
    impl IntoIterator
    when the function only iterates. Application:
    &[T]
    is fine. G#accept-iterators
  • impl Into<T>
    parameters belong in library APIs where call-site ergonomics are paramount. Application code takes
    T
    . G#accepting-into
  • When a
    bool
    argument's meaning is unclear at the call site, make it a two-variant
    enum
    . If you keep the
    bool
    , name it in an inline comment at the call site:
    connect(addr, /* retry= */ true)
    . G#enum-vs-bool
  • Choose the error contract:
    • Option
      when the cause is obvious (
      checked_add
      , a missing value).
    • Result
      when the caller needs the cause to recover (I/O, network).
    • panic!
      for bugs and broken preconditions, which get fixed in code rather than handled at runtime.
    Developer-facing binaries and tests may panic. A codebase may choose
    Result
    even for broken invariants. G#reporting-errors
Types and traits
  • Use a newtype instead of an alias when the semantics differ, the type deserves its own API, the underlying type may change, or values are easy to mix up (
    Day
    ,
    Month
    ,
    Year
    ). G#newtypes-vs-type-aliases
  • Use named fields instead of tuples and multi-field tuple structs. Newtypes and very local tuples are fine. G#prefer-named-fields
  • Library code anticipates the trait impls users will need. Application code adds them on demand. G#traits-yagni
  • A trait exists for a generic bound, for
    impl Trait
    /
    dyn Trait
    in a signature, or as an extension trait. Everything else is an inherent
    impl
    . G#trait-vs-inherent-impl
  • An extension trait is named
    FooExt
    and owned by whoever owns
    Foo
    . A foundational library may extend foreign types. An input trait (
    DateLike
    , implemented on foreign types) is not an extension trait and is fine. G#extension-traits, G#naming-extension-traits
  • Trait impls (G#important-traits):
    • Types with public fields implement the traits all their fields implement.
    • Error types are
      Copy
      whenever no field prevents it.
    • Implement
      Copy
      only when the type will stay
      Copy
      .
    • Most types implement
      Clone
      . Types that represent an external resource don't.
    • PartialEq
      /
      PartialOrd
      give users
      ==
      /
      <
      . Add
      Eq
      /
      Ord
      only for reflexivity or a total order.
    • A likely map key or cache key implements
      Hash
      and
      Eq
      , plus
      Ord
      when the type has a clear total order.
  • If a
    From
    impl is a primary way to build a type, also add an inherent
    new()
    or
    from_foo()
    . G#from-impls
  • An all-pub-field options struct implements
    Default
    so callers can write
    Opts { a: 1, ..Default::default() }
    . Don't mark it
    #[non_exhaustive]
    , which blocks that syntax outside the crate. G#options-should-implement-default, G#non-exhaustive-structs
  • Take an
    #[expect]
    on
    exhaustive_enums
    /
    exhaustive_structs
    for a fixed ontology (
    Color
    ,
    Rectangle
    ), a bool-like two-variant enum, or a type whose breakage you will fix yourself. G#non-exhaustive-enums
  • When matching a foreign
    #[non_exhaustive]
    enum, list every known variant and fold the ones you ignore into the wildcard (
    Shape::Triangle | _ => {}
    ). When you care about only one or two variants, use
    if let
    or
    let else
    . G#non-exhaustive-enum-matching
  • Operator overloads keep their mathematical or logical meaning. G#operator-overloads
Macros
  • Express an API with the first option that works: plain functions, types, traits and modules, then
    macro_rules!
    , then other code generation, then
    proc_macro
    . Count the cost: weaker IDE and search support, a local dialect, harder large-scale changes. G#macros
Naming
  • Lifetimes get descriptive names, especially on types. Use
    '_
    where it works. Single letters are fine for the input-to-output link of one method or a local
    for<'a>
    , at most two of them. G#lifetimes
  • Generic parameters get short names that hint at their main bound (
    R: Read
    ). Use
    T
    /
    U
    only for nearly unbounded APIs such as
    Vec<T>
    . G#generic-parameters
  • Constructors are
    new()
    ,
    new_with_foo()
    for alternatives, and
    try_new()
    when they return a
    Result
    . Conversions are
    from_foo()
    backed by a
    From
    impl. G#naming-initialization-functions
  • Accessors:
    foo()
    ,
    foo_mut()
    ,
    set_foo(v)
    ,
    take_foo()
    (resets the field and returns the old value),
    replace_foo(v)
    (returns the old value), and
    with_foo(|foo| ..)
    /
    with_mut_foo(..)
    . Use the closure form when the field sits behind a
    Mutex
    or
    RefCell
    (so the guard type stays private) or a setter would need to clone a value that can't be cloned. G#getters-and-setters, G#closure-accessors
  • Spell words out. Keep only abbreviations an outsider knows, such as Wikipedia-common ones like
    IpAddr
    . Don't drop letters from a word (
    cnt
    ). G#avoid-abbreviations
Docs
  • A doc says what the code does not. Omit one that restates the name and put
    #[expect(missing_docs, reason = "...")]
    there instead. Self-explanatory enum variants may go undocumented. Don't explain language basics. Examples need to cover the crate somewhere, not every function. Write
    ///
    and
    //!
    by hand rather than generating them from macros. G#writing-doc
  • Use
    //
    for implementation notes and internal TODOs. One item can carry both:
    ///
    for users,
    //
    for maintainers. G#writing-doc
Implementation
  • Write unsafe code only when no safe version exists, and wrap it in a safe abstraction, ideally in its own crate with few dependencies. Write a technical justification, per block or for a whole file or build target: why it can't be safe, and the benchmark if the reason is speed. G#unsafe
  • Treat
    #[doc(hidden)]
    items you don't own as private. G#doc-hidden
  • Nothing runs before
    main()
    : no
    ctor
    crate, no life-before-main tricks. G#global-initialization
  • Annotate enough types that a reader familiar with the codebase can tell what was inferred. Put the type on the binding rather than in a turbofish, especially after
    .into()
    ,
    .parse()
    and long iterator chains. Use
    ::<_>
    where the compiler demands a turbofish. G#type-inference
  • Give an
    assert!
    a message when it can say why the invariant holds, show the offending value, or tell API misuse apart from an internal bug. The message replaces a comment and shows up in logs. A message that only restates the condition adds nothing. G#assertion-context
  • Bind a combinator chain to a named variable before the
    for
    that consumes it. Rewrite long chains with branches or outside mutation as a loop. Keep short chains whose combinator carries the logic (
    any
    ,
    sum
    ). G#combinator-chains
  • Join three or more strings with
    format!
    /
    write!
    rather than
    +
    . Fill a literal template with
    format!
    rather than
    str::replace
    or a homemade template syntax. G#prefer-format-or-write
工具无法检查以下规则。指南为匹配规则指定的 lint 是
non_exhaustive_omitted_patterns
,但它在 stable 1.98 上尚不可用,并且需要 nightly 特性,这会违反禁止 unstable 特性的规则。因此该规则仍以文字形式保留在这里。
模块与导入
  • 仅含一个主要项
    Foo
    的叶子模块应在
    foo.rs
    中定义为
    mod foo
    。G#userdefined-item
  • 非叶子模块只能包含
    mod
    声明和再导出,最多再加少量粘合代码。
    mod tests
    或
    #[cxx::bridge]
    子模块仍视为叶子模块。G#non-leaf-modules
  • 不要定义 prelude。是否使用第三方 prelude 由评审者决定。G#glob-imports
  • 在使用 trait 的函数体内导入该 trait,除非整个文件都在使用它。G#prefer-local-trait-imports
  • 通过所属模块调用自由函数:先写
    use std::mem;
    ,再调用
    mem::swap(..)
    。当名称本身已经明确无歧义(C++ 互操作),或模块名发生冲突时,可以直接调用名称。G#toplevel-functions
  • 类型名不加限定:先写
    use regex::Regex;
    ,再使用
    Regex
    。对于名称有歧义、类型族较大(rustc 的 hir)、宏和生成代码以及庞大的导入列表,应使用模块路径(
    io::Error
    )或重命名(
    IoError
    )。G#type-names
格式
  • #[rustfmt::skip]
    仅用于手动对齐(矩阵、相似行组成的行组)和生成代码。个人审美不能作为理由。G#formatting-optout
  • 字面量中的不可见字符应写成转义形式,例如
    \u{200D}
    。Clippy 0.1.98 不会标记原始零宽连接符。G#formatting-other
所有权与函数签名
  • 将所有权建模为唯一所有者与借用。只有当这种结构复杂到难以合理处理时,才使用
    Rc
    /
    Arc
    ,并应在评审中说明理由。G#avoid-rc-arc
  • Library:返回迭代器(
    impl Iterator
    或具体类型),而不是
    Vec<T>
    。当大多数调用者都需要
    Vec
    、实现自然会构建
    Vec
    、结果将被索引、函数用于构建集合,或函数只是交还已有 vector 时,应返回
    Vec
    。Application:使用
    Vec
    即可。G#return-iterators
  • Library:当函数只负责迭代时,接收
    impl IntoIterator
    。Application:使用
    &[T]
    即可。G#accept-iterators
  • impl Into<T>
    参数应出现在以调用点易用性为首要目标的 library API 中。应用代码则接收
    T
    。G#accepting-into
  • 当
    bool
    参数的含义在调用点不明确时,改用包含两个变体的
    enum
    。如果保留
    bool
    ,则应在调用点通过行内注释命名其含义:
    connect(addr, /* retry= */ true)
    。G#enum-vs-bool
  • 选择错误契约:
    • 原因显而易见时使用
      Option
      (如
      checked_add
      、值缺失)。
    • 调用方需要获取原因以便恢复时使用
      Result
      (如 I/O、网络错误)。
    • 对于 bug 和已破坏的前置条件使用
      panic!
      ;这些问题应通过修改代码解决,而不是在运行时处理。
    面向开发者的二进制程序和测试可以 panic。即使不变量已经破坏,代码库也可以选择使用
    Result
    。G#reporting-errors
类型与 trait
  • 当语义不同、类型需要拥有自己的 API、底层类型可能变化,或值容易被混淆(
    Day
    、
    Month
    、
    Year
    )时,使用 newtype,而不是类型别名。G#newtypes-vs-type-aliases
  • 使用具名字段,而不是元组和含多个字段的元组 struct。newtype 和非常局部的元组可以使用。G#prefer-named-fields
  • Library 代码应预先考虑用户所需的 trait 实现。Application 代码则按需添加。G#traits-yagni
  • trait 应用于泛型约束、函数签名中的
    impl Trait
    /
    dyn Trait
    ,或作为扩展 trait。其他情况均使用固有
    impl
    。G#trait-vs-inherent-impl
  • 扩展 trait 命名为
    FooExt
    ,并由
    Foo
    的所有者负责。基础 library 可以扩展外部类型。输入 trait(如在外部类型上实现的
    DateLike
    )不属于扩展 trait,可以正常使用。G#extension-traits、G#naming-extension-traits
  • trait 实现(G#important-traits):
    • 包含公共字段的类型,应实现其所有字段所实现的 trait。
    • 只要没有字段阻止,错误类型就应实现
      Copy
      。
    • 只有当类型将始终保持
      Copy
      时,才实现
      Copy
      。
    • 大多数类型应实现
      Clone
      。表示外部资源的类型则不应实现。
    • PartialEq
      /
      PartialOrd
      为用户提供
      ==
      /
      <
      。只有需要自反性或全序时才添加
      Eq
      /
      Ord
      。
    • 可能用作 map key 或 cache key 的类型应实现
      Hash
      和
      Eq
      ;当类型具有明确的总序时,还应实现
      Ord
      。
  • 如果
    From
    实现是构建某种类型的主要方式,还应添加固有
    new()
    或
    from_foo()
    。G#from-impls
  • 所有字段均为
    pub
    的 options struct 应实现
    Default
    ,使调用方能够写出
    Opts { a: 1, ..Default::default() }
    。不要将其标记为
    #[non_exhaustive]
    ,否则该语法将无法在 crate 外部使用。G#options-should-implement-default、G#non-exhaustive-structs
  • 对固定的本体(
    Color
    、
    Rectangle
    )、类似 bool 的双变体 enum,或破坏后由自行修复的类型,应对
    exhaustive_enums
    /
    exhaustive_structs
    使用
    #[expect]
    。G#non-exhaustive-enums
  • 匹配外部的
    #[non_exhaustive]
    enum 时,应列出所有已知变体,并使用通配符折叠需要忽略的变体(
    Shape::Triangle | _ => {}
    )。如果只关心一个或两个变体,则使用
    if let
    或
    let else
    。G#non-exhaustive-enum-matching
  • 运算符重载应保持其数学或逻辑含义。G#operator-overloads
宏
  • 按顺序选择第一种可行的方式来表达 API:普通函数、类型、trait 和模块,然后是
    macro_rules!
    ,再然后是其他代码生成方式,最后是
    proc_macro
    。应权衡其成本:IDE 和搜索支持更弱、形成局部专用语法体系,并且更难进行大规模修改。G#macros
命名
  • 生命周期应使用描述性名称,尤其是在类型上。适用时使用
    '_'
    。单字母适合表示某个方法的输入与输出之间的关联,或局部
    for<'a>
    ,最多使用两个。G#lifetimes
  • 泛型参数应使用简短且能提示主要约束的名称(
    R: Read
    )。只有对于
    Vec<T>
    之类几乎没有约束的 API,才使用
    T
    /
    U
    。G#generic-parameters
  • 构造函数命名为
    new()
    ,替代形式命名为
    new_with_foo()
    ,返回
    Result
    时命名为
    try_new()
    。转换方法命名为
    from_foo()
    ,并以
    From
    实现为支撑。G#naming-initialization-functions
  • 访问器:
    foo()
    、
    foo_mut()
    、
    set_foo(v)
    、
    take_foo()
    (重置字段并返回旧值)、
    replace_foo(v)
    (返回旧值),以及
    with_foo(|foo| ..)
    /
    with_mut_foo(..)
    。当字段位于
    Mutex
    或
    RefCell
    之后(从而可让 guard 类型保持私有),或 setter 需要克隆无法克隆的值时,应使用闭包形式。G#getters-and-setters、G#closure-accessors
  • 应拼写完整单词。只保留外界人士已知的缩写,例如 Wikipedia 中常见的
    IpAddr
    。不要省略单词中的字母(
    cnt
    )。G#avoid-abbreviations
文档
  • 文档应说明代码的作用,而不是仅仅重复名称。如果文档只是复述名称,则应省略,并改为添加
    #[expect(missing_docs, reason = "...")]
    。不言自明的 enum 变体可以不加文档。不要解释语言基础内容。示例只需在 crate 的某处提供覆盖,不必为每个函数都提供示例。应手动编写
    ///
    和
    //!
    ,而不是通过宏生成。G#writing-doc
  • 使用
    //
    编写实现说明和内部 TODO。同一个条目可以同时包含两类注释:面向用户的
    ///
    和面向维护者的
    //
    。G#writing-doc
实现
  • 仅当不存在安全实现时才编写 unsafe 代码,并使用安全抽象进行封装,最好放在依赖很少的独立 crate 中。应按代码块、文件或构建目标给出技术论证:说明为何无法安全实现;如果原因是性能,则还应提供基准测试结果。G#unsafe
  • 将不归自己所有的
    #[doc(hidden)]
    项视为私有项。G#doc-hidden
  • main()
    之前不运行任何代码:不得使用
    ctor
    crate,也不得使用任何在 main 生命周期之前运行的技巧。G#global-initialization
  • 应添加足够的类型标注,使熟悉代码库的读者能够判断哪些类型来自推断。应将类型写在绑定上,而不是 turbofish 中,尤其是在
    .into()
    、
    .parse()
    和长迭代器链之后。仅当编译器要求使用 turbofish 时,才使用
    ::<_>
    。G#type-inference
  • 当
    assert!
    的消息能够说明不变量为何成立、展示违规值,或区分 API 误用与内部 bug 时,应为其添加消息。消息应替代注释,并能出现在日志中。仅复述条件的消息没有价值。G#assertion-context
  • 在消费组合器链的
    for
    循环之前,应先将链绑定到具名变量。对于包含分支或在循环外修改数据的长链,应将其改写为循环。如果短链中的组合器本身承载了逻辑(
    any
    、
    sum
    ),则可以保留。G#combinator-chains
  • 三个或更多字符串应使用
    format!
    /
    write!
    拼接,而不是使用
    +
    。应使用
    format!
    填充字面量模板,而不是使用
    str::replace
    或自定义模板语法。G#prefer-format-or-write

Overrides

覆盖规则

When common Rust advice, in another skill or in the codebase, says otherwise, follow Google:
TopicCommon adviceGoogle
Import granularity
imports_granularity = "Crate"
"Module"
(G#use-statement).
group_imports
and
reorder_imports
can stay
unwrap
/
expect
, panics
No
unwrap()
or
expect()
outside tests; avoid
panic!
in production
panic!
for bugs and broken invariants, with
expect
naming the invariant (G#reporting-errors, G#expect-over-unwrap). Enable
unwrap_used
, not
expect_used
Loops vs combinatorsPrefer iterator chains over
for
loops, including chains in a
for
header
for
when clearer, never a chain in the header, avoid
for_each
(G#combinator-chains)
impl Into<String>
params
Use them in constructors and builders everywhereLibrary-only, and only when ergonomics are paramount (G#accepting-into)
Shared state
Arc<Mutex<T>>
/
Rc<RefCell<T>>
for shared mutable state
Unique ownership first;
Rc
/
Arc
only when the alternative is unreasonably complex (G#avoid-rc-arc)
TraitsDesign trait hierarchies; add extension traits to any type, such as
StringExt for str
A trait only for generics,
impl
/
dyn
, or extension; extension traits are owned by the type's owner (G#trait-vs-inherent-impl, G#extension-traits)
Error types
thiserror
enums carrying
String
payloads
Copy
whenever possible (G#important-traits). Give a variant a payload only when the caller needs it
clippy::nursery
Enable
-W clippy::nursery
Allow
derive_partial_eq_without_eq
and
missing_const_for_fn
, which push against G#important-traits and G#const-functions
missing_docs
level
#![deny(missing_docs)]
for libraries
warn
plus
#[expect]
on trivial items (G#writing-doc)
当另一个 skill 或代码库中的通用 Rust 建议与此不同时,应遵循 Google 指南:
主题通用建议Google 指南
导入粒度
imports_granularity = "Crate"
使用
"Module"
(G#use-statement)。
group_imports
和
reorder_imports
可以保留
unwrap
/
expect
与 panic
测试之外不使用
unwrap()
或
expect()
;生产环境避免
panic!
对 bug 和已破坏的不变量使用
panic!
,并用
expect
标明不变量(G#reporting-errors、G#expect-over-unwrap)。启用
unwrap_used
,而不是
expect_used
循环与组合器优先使用迭代器链而不是
for
循环,包括
for
头部中的链
更清晰时使用
for
,绝不在头部使用链,避免使用
for_each
(G#combinator-chains)
impl Into<String>
参数
在所有构造函数和 builder 中使用仅限 library,且仅当易用性至关重要时使用(G#accepting-into)
共享状态使用
Arc<Mutex<T>>
/
Rc<RefCell<T>>
管理共享可变状态
优先采用唯一所有权;只有替代方案复杂到难以合理处理时才使用
Rc
/
Arc
(G#avoid-rc-arc)
Trait设计 trait 层级;为任何类型添加扩展 trait,例如
StringExt for str
trait 仅用于泛型、
impl
/
dyn
或扩展;扩展 trait 由类型所有者负责(G#trait-vs-inherent-impl、G#extension-traits)
错误类型使用携带
String
payload 的
thiserror
enum
尽可能实现
Copy
(G#important-traits)。仅当调用方确实需要时才为变体添加 payload
clippy::nursery
启用
-W clippy::nursery
允许
derive_partial_eq_without_eq
和
missing_const_for_fn
,因为它们与 G#important-traits 和 G#const-functions 的建议方向相反
missing_docs
级别
对 library 使用
#![deny(missing_docs)]
使用
warn
,并为简单条目添加
#[expect]
(G#writing-doc)