Google's Rust Style Guide

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

Google Style Guides Rust Style Guide Rust Style Guide Background Scope Goals of the style guide Follow public Rust style rules Apply API design rules in context Code organization Prefer small crates [chrome] Use flat file layout for rust_library sources [chrome] Name source files and leaf modules after the primary user-defined item Don’t implement APIs in non-leaf modules Don’t use glob imports A use statement should import items from one module Prefer locally-scoped trait imports Qualify calls to top-level functions with a module name Type names should be imported and used unqualified Use the appropriate import mechanism [chrome] Code formatting and aesthetics Use the appropriate formatting tool Opting out of automatic formatting Ownership and borrowing Avoid Rc and Arc Prefer borrows over deep copies Function inputs and outputs Accept flexible references for immutable data Iterators vs. owned collections in return types Iterators vs. slices in function parameters Accepting Into Prefer enum over bool in APIs Reporting errors Types Newtypes versus type aliases Prefer named fields over tuples and non-newtype tuple structs Traits Add trait implementations when they become necessary Implement known standard library traits instead of custom methods Use #[derive()] if possible Generics versus dyn Trait When to define a trait versus an inherent implementation Extension traits Specific guidance for important traits Pair important From impls with explicit constructor methods Options structs should implement Default Concurrency Handling poison Don’t use async / .await [chrome] Don’t start new threads through the Rust standard library [chrome] Use fuchsia_sync::Mutex [Fuchsia] Macros Naming Naming methods Naming lifetimes Naming generic parameters Naming extension traits Naming initialization functions Avoid abbreviations When and how to write documentation Other Rust features Unsafe code No unstable features Getters and setters More on accessors that accept closures Implement expected API sets together Do not access items marked #[doc(hidden)] that you don’t own Use const functions responsibly Avoid overloading for non-mathematical purposes Apply #[non_exhaustive] to publicly-exposed enums Apply #[non_exhaustive] to public structs with public fields #[must_use] on functions #[must_use] on types Do not run code before main() Implementation concerns Don’t overuse type inference Prefer pattern matching over check-then-unwrap Prefer expect over unwrap Don’t omit patterns on non_exhaustive enums when matching Use context strings to clarify assertions Don’t use iterator combinator chains when direct iteration is clearer Don’t call panic::catch_unwind Prefer format! / write! for concatenation and substitution Use the right per-codebase test framework

Google Rust 风格指南。本指南涵盖了背景、范围、目标、公共 Rust 风格规则的遵循、API 设计规则的应用、代码组织(如偏好小型 crate、扁平文件布局)、代码格式化、所有权与借用、函数输入输出、错误报告、类型定义、Trait 使用、泛型与动态分发、并发处理、宏、命名规范、文档编写、不安全代码、Getter/Setter、以及具体的实现注意事项(如类型推断、模式匹配、断言等)。

This document is a style guide for the usage of the Rust programming language at Google. In this context, “style” refers to more than just formatting; it includes guidance on API and implementation design. Rust is used in many places, including google3, Android, ChromeOS, Fuchsia, and Chrome, and we’d like for Rust usage at Google to be consistent both within and across codebases. In addition to bringing consistency to our Rust code, style guidance also helps establish a standard of quality.

本文档是 Google 内部使用 Rust 编程语言的风格指南。在此语境下,“风格”不仅仅指格式化,还包括对 API 和实现设计的指导。Rust 被广泛应用于 google3、Android、ChromeOS、Fuchsia 和 Chrome 等多个项目中,我们希望 Google 内部的 Rust 使用方式在各个代码库之间保持一致。除了提升代码的一致性外,风格指南还有助于建立质量标准。

Background Scope The current scope of authority of the rules outlined in this guide: In Android, Chromium, and other codebases: This style guide has been developed in consultation with other codebases, and they intend to start applying it. These codebases may have their own rules about how strictly this is expected to be applied. Expect more information here as these codebases adopt this guide.

背景与范围:本指南中规则的当前适用范围包括 Android、Chromium 及其他代码库。本风格指南是在与这些代码库进行协商后制定的,它们计划开始应用这些规则。各代码库可能针对执行的严格程度有其自身的规定。随着这些代码库对本指南的采纳,此处将更新更多相关信息。

Goals of the style guide By and large, we have this document for the same reasons we have a C++ style guide. Most style rules come from one or more of the goals listed below. Style rules should prioritize readability and maintainability over writeability We expect our code to be around for long periods of time, and we consider a little bit of extra effort applied during code writing to be worth it in the long run if the style rule improves readability. Style rules should favor better automation Large-Scale Changes (LSCs) are common at Google, and consistency helps make LSCs easier to carry out. Style rules should be consistent with the wider Rust ecosystem where possible The broader Rust ecosystem already has a pretty good amount of consistency in style, and we should rely on that where possible to reduce surprise and make it less work to learn Google’s Rust style. Style rules should pull their weight Every Rust developer and reviewer at Google has to keep these style rules in mind: as such, we should be careful to include rules that have a tangible benefit. Style rules may help avoid minor style disagreements There are many cases where reasonable people may disagree about a style, and we expect that disagreement to show up often on CLs. Having a style rule helps avoid having to rehash this each time. Rules in this category that do not have other benefits should be kept to a minimum.

风格指南的目标:我们制定这份文档的原因与制定 C++ 风格指南的原因大致相同。大多数风格规则源于以下一个或多个目标:风格规则应优先考虑可读性和可维护性而非编写速度;风格规则应有利于自动化,一致性有助于简化 Google 常见的大规模变更(LSC);风格规则应尽可能与更广泛的 Rust 生态系统保持一致,以减少学习成本;风格规则应具有实际价值,确保每条规则都能带来切实的好处;风格规则有助于避免琐碎的风格争议,通过预先设定规则,减少在代码审查(CL)中反复讨论风格问题的必要。

Follow public Rust style rules Follow the official public Rust style rules to the extent they don’t conflict with this style guide. Rust Style Guide Most code formatting conventions are enforced automatically by rustfmt. Rust API Guidelines A “conflict” would be a case where this style guide suggests a pattern that is discouraged, or counter to the primary encouraged pattern in the Rust style guide. Why does the guidance in this style guide deviate from regular Rust style rules? Most style guides have three goals: consistency, readability, and encouraging good API design. Regardless of the specific choices made, it helps everyone to have these choices made beforehand to limit bikeshedding. This style guide shares those goals, but it also has an additional goal not seen as often: smoothing the way for Large-Scale Changes (LSCs). Large codebases like many of the ones at Google occasionally need to run

遵循公共 Rust 风格规则:在不与本指南冲突的前提下,遵循官方的公共 Rust 风格规则。大多数代码格式化约定由 rustfmt 自动强制执行。所谓的“冲突”是指本指南建议的模式与 Rust 风格指南中鼓励的主要模式相抵触的情况。为什么本指南的建议会偏离常规的 Rust 风格规则?大多数风格指南都有三个目标:一致性、可读性和鼓励良好的 API 设计。无论做出何种具体选择,预先做出决定都有助于限制无意义的争论(bikeshedding)。本指南不仅共享这些目标,还有一个不那么常见的目标:为大规模变更(LSC)铺平道路。像 Google 这样的大型代码库偶尔需要运行……