references/google-rust-style-guide.md
GitHubGoogle Rust Style Guide (digest)
Source: https://google.github.io/styleguide/rustguide.html . Google's internal guide, also adopted by Android, Chromium, and Fuchsia. It defers to the official Rust Style Guide and API Guidelines and adds rules on top. API-design rules are binding for library code and a strong recommendation for application code, which "should generally favor simplicity and directness over broad reusability". Read this for formatting, imports, module layout, accessor naming, and the application-vs-library distinction. Rules specific to Chromium or Fuchsia builds are omitted below.
Background and goals
Readability over writeability; automation (large-scale changes should be mechanical); consistency with the Rust ecosystem; rules must pull their weight. Follow the official Rust Style Guide and API Guidelines unless this guide conflicts. rustfmt enforces most formatting automatically.
Code organization
Prefer small crates, ideally but not necessarily a single file. Larger crates are allowed for orphan-rule coherence or foundational libraries. Decide crate boundaries before submodules; the root may re-export from leaf submodules.
Name a leaf module after its primary item:
Foogivesmod foo/foo.rs.Non-leaf modules contain only
moddeclarations and re-exports. Small "ties things together" code is tolerated. Leaf modules may includemod tests.No glob imports, except at reviewer discretion:
use super::*in inline modules,use Enum::*in enum method bodies,pub use submodule::*in non-leaf modules. Avoid defining preludes.One module per
usestatement (rustfmtimports_granularity = Module): no::inside braces.use foo::bar::{Bar, Baz}; // OK use foo::{Foo, bar::Bar}; // avoidImport traits inside function bodies unless the trait is used throughout the file.
Qualify free function calls by module (
mem::transmute(y), nottransmute(y)), but use types and traits unqualified (Regex, notregex::Regex). Exceptions: ambiguous names such asio::Error(oruse std::io::Error as IoError), large type groups, macros and generated code.
Formatting
- Always run the formatter. Recommended rustfmt settings:
max_width = 100,hex_literal_case = Lower,format_macro_matchers = true. #[rustfmt::skip]only for deliberate manual alignment or generated code, never for personal style.
Ownership and borrowing
- Avoid
Rc/Arc; prefer unique ownership. Exception: when the alternative is unreasonably complex, a review judgment call. - Borrow rather than
.clone(). Clone when a real deep copy is needed or borrowing becomes excessively complex, and weigh performance. CloningRc/Arcis expected.
Function inputs and outputs
- Accept the most flexible borrowed type:
&[T]not&Vec<T>,&strnot&String,&Tnot&Box<T>,Option<&T>not&Option<T>(clippyborrowed_box,ptr_arg). - Library code returns iterators (concrete or
impl Iterator) instead ofVec<T>and acceptsimpl IntoIteratorwhen only iterating. Application code may return or takeVec/&[T]when simpler. Exceptions: callers need an owned vector, random indexing, or the function's purpose is building a collection. impl Into<T>parameters only where call-site ergonomics are paramount, weighed against code bloat. Application code should almost never use them.- Use an
enuminstead of aboolparameter when the purpose isn't obvious. If you keep abool, add an inline comment at the call site. - Errors, chosen by API contract:
Optionfor obvious failures (checked_add);Resultwhen the caller needs details (fn open_file(path: &Path) -> Result<File, io::Error>);panic!for bugs and violated invariants, which must be fixed in the code, not handled at runtime. Developer-facing binaries may panic on non-fatal errors; tests may panic for assertions.
Types
- Use a newtype rather than an alias for notable semantic differences, a type needing
its own API, a possible future change of underlying type, or type safety
(
Day/Month/Year). - Prefer named fields over tuples, since
.0and.1get confusing. Exceptions: single-field newtypes and very local contexts.
Traits
- Add trait impls when needed. Low-level library code anticipates needs; application code adds them on demand.
- Implement the std trait instead of a custom method:
impl FromStr for Foo, notfn from_str(clippyshould_implement_trait). Keeping both is acceptable. - Use
#[derive]wherever it can express the impl. - Library code accepts generics (
T: Trait,impl Trait) overdyn Trait, except when code size matters. Reasons: vtable indirection, no inlining, and some traits are not dyn-compatible (generic functions, associated functions withoutself, functions returningSelf). - Define a trait only for generic programming, for accepting or returning
impl/dyn Trait, or as an extension trait. Otherwise use an inherent impl. Don't use traits merely to organize code. - Extension traits: suffix
Ext, sole purpose is adding methods (not for generics ordyn), owned by the team that owns the extended type. - Trait guidance: types with public fields implement traits all subfields implement.
Error types:
Copywhen possible.Copywhenever it will clearly stayCopy;Clonefor most types except external resources;Defaultwhen there is anew()or default state (clippynew_without_default);PartialEqoverEqunless you need reflexivity;PartialOrdoverOrdunless you need a total order; map keys getHashandEq, plusOrdif there is a clear total order. - Pair an important
Fromimpl with an inherent::new(),::new_from_foo(), or::from_foo(). - Bag-of-options structs with all-public fields implement
Default, enabling..Default::default().
Concurrency
- Never reach inside a poisoned mutex, "no matter how tempting".
- Library code should not start threads itself.
Macros
Preference order: plain functions, types, traits, and modules; then macro_rules!;
then other codegen; then proc_macro. Weigh IDE and code-search costs, dialect
creation, and difficulty of large-scale changes.
Naming
- Methods follow std style:
as_,to_,into_with the matchingselfconvention (clippywrong_self_convention). - Lifetimes should be descriptive, especially on types. Exceptions: generic abstractions
like
Cow,'_, and single-character names for simple input/output relationships. - Generic parameters: short, related to what they represent, ideally the letter from the
most important bound.
T/Ufor APIs meant for almost any type. - Constructors:
new()ornew_with_foo();try_new()if fallible. Value-to-value conversions:from_foo()with aFromimpl. - Avoid abbreviations outsiders won't know, including acronyms and letter-dropping.
Exceptions: Wikipedia-common terms and clear cases like
IpAddr.
Documentation
Document public APIs; consider the
missing_docslint.Include examples somewhere in the crate, not necessarily on every function.
Document panics caused by malformed input, and invariants of unsafe functions and traits.
Use capitalization and punctuation. Don't explain language basics. Comments must add information:
/// Removes an element.onremove_element()is bad; omit it or allow the lint. Enum variant docs are often omittable.///for items;//!at the top of a file for modules and crates; Markdown;//for implementation notes, TODOs, and commented-out code. Mixing///and//on one item is fine:/// Finds the first `FooItem` with the given `name`, or `None` if not present. // TODO(issue-12345): `name` should be &str, not String.Prefer plain doc comments over macro-generated docs.
Other Rust features
- Unsafe: don't write it unless safe code cannot do the same. Wrap it in a safe
abstraction, isolate it (ideally in its own crate with few dependencies), add a
SAFETY:comment, and justify it, with benchmarks if performance is the reason. - Unstable features: don't use them.
- Accessors:
foo()returns the value or a reference,foo_mut(),take_foo(),set_foo(T),replace_foo(T) -> T, andwith_foo(|f| ..)/with_mut_foo(|f| ..)for closure access. Closure accessors suit interior-mutability wrappers (Mutex,RefCell) or follow-up validation whereset_foocan't be used. - If you implement
len(), also implementis_empty()(clippylen_without_is_empty). - Don't access
#[doc(hidden)]items you don't own. - Mark a public function
constonly if it will stayconst; removingconstis breaking. - Overload operators only for their mathematical or logical meaning, not as sugar.
#[non_exhaustive]on public enums and public-field structs used across teams. Exceptions: stable ontologies (Color), two-state enums, or a commitment to fixing breakage with a large-scale change (clippyexhaustive_enums).#[must_use]on functions when ignoring the return is a misuse (pure functions likeHashMap::get()) or the return carries errors or critical info; not needed if the return type already has it (Result). On types returned by such functions: error types and lazy computations.- Run no code before
main()(noctorcrate).
Implementation concerns
Don't overuse inference. Add explicit types for
.into(),.parse(), and complex iterator results. Prefer typed variable declarations to turbofish; use_where the compiler forces a turbofish.Pattern-match instead of check-then-unwrap:
if let Some(value) = option { .. }, notis_some()followed byunwrap().Use
expect("reason")overunwrap()when a panic is unavoidable.On
#[non_exhaustive]enums, list every variant you handle, with a wildcard for the rest. Useif letorlet .. elsewhen you care about one variant (lintnon_exhaustive_omitted_patterns).Add context strings to
assert!, especially when a human will see the failure or to distinguish API misuse from bugs:assert!(self.stream.is_some(), "Call connect() before executing queries");Don't repeat the condition as the message.
Avoid long or complex iterator chains. Don't put a chain in a
forheader; bind it to a variable first. Avoidfor_each. Short chains are fine:values.iter().any(|&v| v > threshold).Don't call
panic::catch_unwindin first-party code, except as defense in depth that is never relied on, and only wherepanic = "unwind"applies.Use
format!/write!to concatenate more than two strings (format!("{a}{b}{c}")) and for substitutions instead ofstr::replace.
Tests
Use the codebase's test framework. Tests may use panics for assertions. Tests live in a
mod tests inside leaf modules.