r/learnrust • • 28d ago

Google published its internal Rust style guide

Google just published its Rust style guide, which it says is developed in consultation with Android, Chromium, Fuchsia and Chrome. Most of it is uncontroversial, but a few rules go against what most of the ecosystem does:

  • Flat file layout. Crates live in a single directory with no subdirectories. If you feel the need to organise a crate into folders, Google says that's a sign the crate is too big and should be split.

  • No glob imports, except for merging C++ namespaces.

  • Avoid Rc and Arc. Prefer unique ownership and borrowing. Google explicitly says engineers coming from other languages reach for shared ownership too quickly.

  • No async/.await in Chromium, and don't start threads through std.

  • Avoid panics, prefer expect over unwrap to document the invariant, and never use catch_unwind.

  • Library vs application code. API design rules are binding for libraries but only a strong recommendation for apps, where simplicity should win over reusability.

  • Don't use traits to organise code. Traits are for generics, impl Trait/dyn Trait, and extension traits.

The stated reason for the deviations is Large-Scale Changes. Google wants code that tooling can refactor across the entire codebase, which explains the flat layout and the anti-glob-import stance more than readability does.

Update

Forgot to attach the link https://google.github.io/styleguide/rustguide.html

454 Upvotes

65 comments sorted by

48

u/Anaxamander57 28d ago

(quote from the style guide not in the post)
Prefer small crates in Chromium; ideally, but not necessarily, a single file (focusing on one abstraction). If your code can be split up into small crates, do so.

As someone who has never written software for a business this suggestion that a crate should "ideally" be a single file sounds totally insane. Do people really do this?

52

u/Sky2042 28d ago

The rule is to support compilation speed, since crates are the unit of compilation. (They give this rationale directly at the end of this section.)

It seems like a reasonable rule to have stated as a preference.

20

u/NeuroSynchroBonding 28d ago

Especially if you have your own build system that makes having lots of small crates easy.

2

u/Anaxamander57 28d ago

I see, so its in order to avoid having to recompile everything every time. Yeah I've dealt with anything where compilation took more than a minute or so.

8

u/elprophet 28d ago

This is definitely a Blaze/Bazel specific rule, made possible by excellent tooling. On the outside, moving a pub mod to a crate is a hassle (entire new cargo.toml!). Inside, automated tooling "just does it".

3

u/garagedragon 28d ago

As a preference, sure? But rigidly adhering to it would make difficult any sort of encapsulation where you have some types used within a larger module, but only within that module, and want the types to only be visible within that module or want them to have access to the larger module that other public uses don't have.

13

u/Sky2042 28d ago

Yes, that's why it says "Prefer small crates". :P

8

u/CrazyKilla15 27d ago

Google has proprietary developer tooling and a developer experience its impossible to imagine if you've never worked there and which does not exist outside of Google. They also have fleets of servers building code for people, checking it, applying rules, so on; They work in teams, too.

Its much, much easier inside google than it may seem, because they built tools and processes to make it easy.

3

u/shahms 28d ago

Google's build system allows you to enforce visibility restrictions between crates.

1

u/frankster 26d ago

rigidly

Fortunately their guidance states "ideally, but not necessarily" which leaves plenty of scope for discretion 

1

u/Chaos_Slug 27d ago

But won't the linker end up linking lots of .a files as opposed to lots of .o files?

1

u/OscarCookeAbbott 28d ago

If you can break something cleanly down into cohesive and compact single file crates I’d say it makes sense, at scale.

16

u/manpacket 28d ago

How do you use traits to organize code?

27

u/funkdefied 28d ago

Java devs sometimes reach for interfaces with no methods to help communicate intent. The natural Rust equivalent is to create empty traits.

Example (forgive bad formatting. I’m on my phone).

/** anything that can be returned by our external service */
trait APIResponse {}

struct QueryEndpointRes { /** … */ }
impl APIResponse for QueryEndpointRes {}

struct NewRecordRes {/** … */ }
impl APIResponse for NewRecordRes {}

In this example, the “APIResponse” trait is purely logical. It has no meaning to the final compiled product. 

5

u/DatBoi_BP 28d ago

I'm somewhat of a newbie to Rust (2 years of personal project use in my spare time).

Is this preferable to making an APIResponse enum with QueryEndpointRes and NewRecordRes variants? If so, why? (If the reason is space, then substitute `T` for `Box<T>` for the two types)

7

u/siva_sokolica 27d ago

Some ideas:

  • It helps communicate intent clearer. Saying that QueryEndpointRes is an APIResponse helps communicate intent without cluttering docs.

  • It adds convenient extension points --- if you want to add a new ontological requirement, ie. fn status on all APIResponses, it's easy to add that into the trait and implement it everywhere.

  • It helps monomorphization. Suppose a time comes when you need a generic function that returns the size of the APIResponse, it's quite easy to write fn sizeof(impl APIResponse) and add a ByteSized super trait on APIResponses. Perhaps you don't even need that if you go down the point above

PS. Boxing seems good at first but necessitates pointer indirection, which a monomorphized approach can avoid in some cases.

3

u/DatBoi_BP 27d ago

Great points, thank you

2

u/Alive_Technician5692 27d ago

Usually referred to as a marker interface.

1

u/Gio_Cri 23d ago

i have seen it come handy mostly for marking Fn categories so TraitX: Fn(...)->...{}

2

u/diplofocus_ 28d ago

I'm guessing by breaking up a large impl block into multiple traits with a single implementor. I've done it once because big file scary, but it just added overhead of remembering which file has the method I wanted.

2

u/SirKastic23 28d ago

big file scary

many small files scarier

1

u/bleachisback 28d ago

I think they mean solely for the sake of code reuse in default impls?

1

u/braaaaaaainworms 27d ago

By copying C++ and separating "interface" from "implementation"

1

u/DavidXkL 27d ago

It's a way to split code out modularly

16

u/theMachine0094 27d ago

I just don’t get all the people claiming these points (listed by OP) go against what most of the eco system does, and that it is mean to help AI. Absolute nonsense.

I have a systems programming background (C/C++) and have written Rust this way from the beginning. Way before AI was relevant in conversation. I know other systems programmers who were my mentors who’d written software like this for decades.

5

u/CrazyKilla15 27d ago

Most people here are self taught and/or hobbyists without professional experience working in large organizations and teams where these systems and processes are more standard. Its only a few notable community crates that really went all in on dozens of optional sub-crates, though they do exist.

3

u/Vorrnth 27d ago

Yeah, that's pretty much how I developeded c++ for decades now. It fits rust too.

1

u/fisothemes 23d ago

I wouldn't recommend writing rust like you would with c++ or zig. They're different languages and they work the way they do because of their limitations. 

7

u/numberwitch 28d ago

Pretty sensible

7

u/Headbanger 28d ago

A noob here. Could someone explain how you avoid using Arc and how you start threads without std? Also why no async/await?

32

u/funkdefied 28d ago edited 28d ago

Not all Arc/Rc is bad. The issue is when you use them as an escape hatch from compiler errors—specifically the “this value doesn’t live long enough” error. 

The “no std threads” and “no async/await” is Chrome-specific. Chrome seems to have its own green-threads runtime called “sequences,” which doesn’t use async/await. The rule is to use a Chrome-managed green-thread rather than OS threads or other concurrency strategy.  https://chromium.googlesource.com/chromium/src/+/HEAD/docs/threading_and_tasks.md#Prefer-Sequences-to-Physical-Threads

1

u/Maybe-monad 27d ago

Not all Arc/Rc is bad. The issue is when you use them as an escape hatch from compiler errors—specifically the “this value doesn’t live long enough” error.

The performance penalty is small but it adds up.

9

u/Anaxamander57 28d ago

You can write a ton of stuff without using Arc and when you do use Arc you lose some of the advantages of Rust. Google is probably just encouraging its programmers to look for idiomatic solutions rather than picking a tool that makes Rust feel more like another language. There are times when Rc/Arc are what you need, of course.

9

u/SirKastic23 28d ago

If you're using Arc it's likely because you have some data that needs to be shared between 2 or more processes. Think about what that data is and how each process uses it

Nowadays, most often than not, I use channels where I would have used Arc, and it drastically simplifies the code and the reasoning necessary

9

u/loaengineer0 28d ago

If the Future is properly scoped, you can pass a non-static immutable reference and you don’t need Arc. Unfortunately, Tokio doesn’t have any facility for spawning scoped Futures. You end up needing Arc for compatibility with a lot of the ecosystem, not because of some fundamental language design problem.

1

u/tabbekavalkade 24d ago

Arc is completely fine. But if you have a choice between Arc and using a reference (borrowing), you don't use Arc. I assume the advice is for people coming from Java.

If you have used C/C++ or similar before, my advice would be the opposite: You probably need Arc more than you think.

Arc makes the compiler generate an instruction with a lock prefix, which can slow down the CPU when there is massive contention (such as Google running the program on 24, 64 or even 128 cpus). For most people, this does not matter.

2

u/jarjoura 26d ago

Flat crate layout makes sense in the giant Google mono repo managed by something like Bazel. Subdirectories still exist there too, just one level removed from Cargo. I don’t think that should apply to community led GitHub style projects that grow and morph over time.

6

u/masterarrows 27d ago

Flat layout vs. systemic complexity: In practice, rejecting nested directories means degrading into a clutter of dozens of .rs files dumped in a single directory. The Rust compiler and module system were explicitly designed with hierarchy in mind to provide clean logical isolation.

Traits strictly for polymorphism: Banning traits for code decomposition and encapsulation fundamentally undermines the Dependency Inversion Principle (DIP) and proper unit testing via mocking. The codebase risks devolving into a tightly coupled monolithic mass.

The crusade against Arc / Rc**:** Fighting shared ownership is noble in theory, but in practice—especially in async contexts or complex ownership graphs—avoiding Arc drags developers straight into a lifetime hell ('a), fighting the borrow checker at every step.

4

u/-Redstoneboi- 27d ago

did you write this

-1

u/masterarrows 27d ago

No, developers can’t write )))

2

u/cornmonger_ 27d ago

the flat layout is the one thing i would completely disagree with. wait until they see what crate clutter looks like using that convention.

1

u/VeprUA 27d ago

Traits strictly for polymorphism: Banning traits for code decomposition and encapsulation fundamentally undermines the Dependency Inversion Principle (DIP) and proper unit testing via mocking. The codebase risks devolving into a tightly coupled monolithic mass.

I wholeheartedly agree with this. What alternative are they offering? rust doesn't do OOP so if you need to do a migration or support multiple providers that contain the same behavior, traits is where its at.

1

u/WhiskyDelta14 26d ago

Well, the rust compiler and module system failed to make the module the compilation unit, so there you go.

1

u/ZachVorhies 27d ago

This is like cpp style guide - fundamentally broken

1

u/Laugarhraun 28d ago

Glob imports are forbidden in all languages at Google fyi.

1

u/psioniclizard 27d ago

Makes a lot of sense, it would be a pain to maintain

1

u/Valuable_Victory_271 27d ago

Is avoiding panics really a necessary inclusive in a style guide?

3

u/nderflow 27d ago

For Google yes. Nobody wants www.google.com to serve a 500 because somebody wants to skip thinking about error handling and deal with it on a later change.

For organizations which aren't Google, well they can do what they want, Google isn't writing their style guide.

2

u/HyperCodec 27d ago

I reckon their competitors do want that

1

u/Valuable_Victory_271 27d ago

I mean no one wants to have their code panic. Error handling is a part of any product so including it seems redundant

2

u/nderflow 27d ago

Right but it also means no use of other similar things in production code paths, such as - I assume - `assert!`.

Different parts of Google take different approaches to "cannot happen" scenarios. See https://chromium.googlesource.com/chromium/src/+/main/styleguide/c++/checks.md for the position for C++ code in Chromium, for example.

Most Google C++ code bases I've worked with personally entirely forbid the use of fatal assertions in production code. Inside Google, Rust and C++ occupy the same "ecological niche" in effect, so it's not surprising that they bothered to document this particular policy for Rust code.

0

u/Due_Block_3054 27d ago

panics make sense to catch programming errors in development.

1

u/solaris_var 27d ago

Panic makes sense for unrecoverrable errors, and a system that restarts your program immediately on panic, in a hopefully timely manner.

Most errors are recoverable, and for those a panic is not justifiable

1

u/Zaurble 27d ago

First time I’ve seen a corpo use good standards

1

u/Murky-Bank2341 27d ago

The panic avoidance rule is nonsense for internal tooling. You lose the entire safety net that Rust offers by treating every error as a recoverable state

1

u/AnArmoredPony 24d ago

the great slop factory published slop production guidelines

1

u/Tekn0z 23d ago

panic = "abort" is the one best thing I'd take from this.

1

u/fisothemes 23d ago

I am not a big fan of the flat layout rule written as is. That should be left up to the judgment of the developer/team. If it gets written down people get dogmatic about it.

The rest feel Chromium/Application specific. Which is fair. 

-5

u/onlyesterday16 27d ago edited 27d ago

These rules are obviously for code to feed AI better

2

u/Xatraxalian 27d ago

How are you going to write concurrent code without Arc, if you don't want to completely torture yourself?

2

u/ART1SANNN 25d ago

seems like it’s not a blanket ban on Arc, just avoiding it unless necessary (ie concurrent code). From the actual style guide:

> Engineers coming from other languages might tend to use Rc and Arctoo quickly.

1

u/PuzzleheadedTower523 27d ago

Genuine, i also thought sometimes, like how we can write it, actually..