Rust Style Guide

(google.github.io)

288 points | by kaycebasques 13 hours ago

21 comments

  • japgolly 5 hours ago

    Apply #[non_exhaustive] to publicly-exposed enums seems like a crazy recommendation to me. So much of the power of enums is that when you add a new case the compiler will flag all pattern matches that you need to update, which is a good thing because you're forced to consider each case. Having a catch-all saves dev-time but it risks not appropriately handling new cases becoming a runtime issue instead of a compile time error.

    • rendaw 2 hours ago

      What people seem to be missing here is that enums are just a reflection of functionality. If you make your enum non exhaustive then add a field, and something stops working because it's now missing critical messages, it's still a breaking change!

      It's always up to callers to decide to handle everything, or decide that additions are non-fatal and use a wildcard branch to ignore them. The same enum could need to be exhaustive for one use case, or subset matched by another.

      • eptcyka 26 minutes ago

        Swift gas a facility for this type of thing, Rust could adopt it too.

        • froh 54 minutes ago

          can't you explicitly express a catch-all in a check?

          edit: I don't know rust. in other languages he's such catch all patterns exist and you have to either capture each possible value explicitly or you express "here in this fu, I take care of these and all others I do that..."

          • mort96 7 minutes ago

            Yes you can, but if a new enum value appears, there's probably something you want to do in response which your default case didn't do.

          • alfiedotwtf 2 hours ago

            Adding a field and it stops compiling > adding a field and it stops working

          • i2talics 4 hours ago

            It's a double edged sword because without #[non_exhaustive], adding a variant becomes a major semver breaking change. It depends on your priorities. I think that there is probably a subtle difference between enums that are expected to gain variants in minor releases (a common example is error types) and enums that are expected to be closed (something like Option or SocketAddr).

            Honestly what I tend to see is that most enums are not exposed publicly at all besides maybe error types and configuration options (where the user usually constructs but does not match on them). In both cases #[non_exhaustive] is valid. For all of the non-public enums you get to enjoy the compiler exhaustiveness enforcement.

            • mort96 4 minutes ago

              In many cases, adding a field should be a semver breaking change because there's usually something your users want to do in response which a default case doesn't handle.

            • ninkendo 4 hours ago

              The corollary to your point is that you have to be extremely cautious what enums you make into public API if you want to be serious about backwards compatibility… likely wanting to include more flexible variants like “unknown” or “generic”, to make your API more flexible. But this ends up being the same problem by a different name, because it still turns things into runtime bugs, just like non-exhaustive enums do.

              It’s the eternal struggle between flexibility and strictness that doesn’t really have a silver bullet answer. Or maybe it’s better framed as “flexibility, safety, backwards compatibility, pick any two”?

              • ozgrakkurt 30 minutes ago

                Wow! The type system might not catch a problem but you will have a stable api! God forbid

                • akshayshah 4 hours ago

                  Sensible attitude for a one-team codebase, but much harder in a google3-sized megarepo…plus the policy matches protobuf enum semantics.

                  • Thom2000 2 hours ago

                    FWIW this future lint `non_exhaustive_omitted_patterns` will help a bit: https://github.com/rust-lang/rust/issues/89554

                    • Groxx 3 hours ago

                      It's usually not too hard to work around stuff like this - wrap it and map it to an exhaustive type, and use tests to ensure that your `unreachable!()` is correct.

                      • quotemstr 2 hours ago

                        This is from the people who make mandatory protobuf fields "optional".

                        I just fundamentally disagree with Google on how to evolve data structures. Sloppy open-domain protobuf field presence, enum values, whatever are illusory extension points. Better to have discrete versions of a data structure --- Foo1, Foo2, Foo3, etc., and rigid checking in each one than to have just one "Foo" with optional-everything that changes implicitly over time.

                        • zeroCalories 3 hours ago

                          Why? Their justification seems reasonable to me. If other teams depend on your enum then you could end up in two really bad cases. First is that you end up having to fix a ton of code just to update your enum, which has it's own headaches. Second is another team's build starts to fail when they update dependencies. Horrible churn to cause for your org. Better to just have them design around non_exhaustive.

                          • Pavilion2095 1 hour ago

                            There is already a catch-all option if you don't need exhaustiveness in some part of your code.

                            • alfiedotwtf 1 hour ago

                              > you could end up in two really bad cases. First is that you end up having to fix a ton of code just to update your enum, which has it's own headaches. Second is another team's build starts to fail when they update dependencies

                              If you really don’t care about compiler warnings, what’s the actual point of using Rust?

                              • zelphirkalt 1 hour ago

                                The first one is not a "really bad case", but the intention of having a strict enum. You want to be force to update, in order to not miss any places, where the change could cause an error. That's the very benefit of it.

                                Second case is the same. The other team needs to definitely know, that their assumptions expressed in their current code are broken and need to be adjusted.

                                We just need to stop to take whatever shit Google is doing as the one bar to measure all others, and need to understand that they may be different requirements than a typical business. We are not Google.

                            • monocasa 12 hours ago

                              Can anyone expand on the chromium specifc guidelines on super tiny crates, particularly no nesting of modules/source files?

                              That feels like the ~2010 era of people saying that functions should be as small as possible. That lead me to reviewing a lot of code where every function was one or two lines and you couldn't actually see what was going on anymore through the layers of unneeded abstraction.

                              I want to give chrome the benefit of the doubt, but that seems really goofy.

                              • evmar 11 hours ago

                                In Cargo-built Rust, a crate is costly in terms of abstraction because it needs its own directory, Cargo.toml, src/ subdir, etc. In the Google build systems I've worked with in the past (and it looks like Chromium follows) they instead put source files in the same directory mixing languages and with finer-grained libraries as they see fit.

                                Given that a crate is the unit of build parallelization in Rust, there's a benefit to more crates especially when they don't cost much cognitive overhead. You could imagine using crates in the way you'd typically use separate mods in a normal Rust project.

                                I dug around in their code search to find some examples but didn't see much Rust in there, seems still early. I think https://source.chromium.org/chromium/chromium/src/+/main:tes... has ~4 Rust files that end up separate crates though. (One of them defines a proc macro so even in a Cargo built Rust project it would need to be in its own separate crate, I think!)

                              • skohan 12 hours ago

                                It might have to do with optimizing compile times. A crate is the unit of compilation, so small crates increase the likelihood that you won't end up recompiling a lot of unrelated code.

                                I guess smaller crates and avoiding nested modules could also help optimize for making the code greppable by coding agents without blowing up context windows.

                                • i2talics 11 hours ago

                                  The granularity of crates shouldn't really impact what kinds of abstractions you build. You can still have as many modules and types as you need, and as big of functions as you need, but its saying you should organize the modules into separate crates instead of one large crate. They even call out the trait coherence rules, saying that you can just make your library bigger instead of forcing a more awkward design in the pursuit of a smaller crate.

                                  I think one benefit of small crates is that it gives you more granularity in linking and dependency graphs, which is especially relevant for rebuilds. At a previous job we had a monolithic "utilities" crate, and this caused problems when you tried to depend on it for the IP address utilities but this brought in the radio frequency utilities. When one of these submodules got an update the versioning would excessively propagate downstream to every consumer. If this was organized as small "net-utils" and "rf-utils" crates then maybe it would not have been as much of an issue.

                                  • loeg 12 hours ago

                                    Maybe one or two line functions are a totally different scale than "all source code files in a crate"? So like, one is problematic in a way the other is not. And the guidance is "prefer small," not "always super tiny." See: "Larger crates are allowed" later on. And also see: "Rationale: Fine-grained library targets are recommended in Chromium due to the massive size of our codebase, non-local effects of adding dependencies in the build graph, and to improve performance of parallel compilation and build caching."

                                    • vvillena 11 hours ago

                                      This being Google, I assume everything goes into a single gigantic monorepo that gets thrown at Blaze. If the unit of compilation is the crate, it makes sense for them to prefer that crates are as small as possible.

                                      • hugmynutus 5 hours ago

                                        blaze/bazel doesn't support incremental crate compilation. It also can't, by design, as incremental compilation depends on incremental change to local build artifacts which isn't deterministic.

                                        So a single crate has to be as small as possible so builds are fast & cachable.

                                        • pornel 10 hours ago

                                          You get stricter enforcement of public APIs and dependencies. You can't import anything you haven't declared as a dep, and cycles are impossible. Rustdoc by default shows only your intended public API.

                                          OTOH if you have one crate with lots of modules, it's tempting to import anything anywhere and use pub(crate). Rustdoc needs to be configured to show private items if you want to see internal APIs.

                                          • tcdent 10 hours ago

                                            Exactly. Being able to organize your code in a way that provides distinct responsibilities per crate is just good practice.

                                            And then the ability to enforce a formalized layer between crates and the way that they assemble into your application (i.e. the public API) is powerful for comprehension and maintainability. I go as far as documenting each crate with its own README that presents it as a standalone component with usage instructions, much like an open source library, even if it's only ever used in a single system.

                                          • skavi 9 hours ago

                                            Forces better code structure in my experience (ignoring orphan rule). modules can have dependency cycles and things get tangled together. crates disallow cycles.

                                            • dnautics 12 hours ago

                                              Compilation speed?

                                            • epage 10 hours ago

                                              > Type names should be imported and used unqualified

                                              This just pushes people to have redundant information in types (`IoError` instead of `io::Error`).

                                              Unless a type is widely recognized (like `HashMap`), I prefer to have them fully qualified so I have the contextual meaning for it. If I am working with a generic name like `Source`, what does that mean? I shouldn't have to look up in the imports to understand the code (or only understand it through an LSP).

                                              Reducing imports also reduces unnecessary merge conflicts.

                                              • boxed 44 minutes ago

                                                Having (hobby) worked with ObjectiveC/Cocoa and then later in Swift, I must say that although NSString looks ugly, it's glorious when it comes to trying to search for anything compared to String.

                                                • Blikkentrekker 10 hours ago

                                                  It says below that that in cases of things like `io::Error` it should be used as that though, as in “cases of ambiguities”. It specifically speaks of not using `regex::Regex` but just `Regex` which seems more reasonable to me.

                                                  • B-Con 8 hours ago

                                                    Google's style guides tend to reduce namespace redundancy.

                                                    Everyone remembers finding some hideous name like foo.widget.widgetBuilder.widgetFactory in Java or something. It's nice to have naming rules, or at least guidelines, focused on trimming redundancy and keeping the signal high.

                                                  • epage 9 hours ago

                                                    That guideline is in response to an API design. I'm speaking to how the default stance (import types) feeds back into API design.

                                                  • wtetzner 10 hours ago

                                                    Honestly I think having blanket rules in either direction is a bad idea. Sometimes it makes sense to qualify things, sometimes it's clearer if you don't.

                                                  • preommr 10 hours ago

                                                    Google has lost a lot of it's sheen for me. It's not really the 2010s anymore where their brand really used to mean something as a step above all the other tech companies.

                                                    Nowadays, I care about their recommendations as much as the ones from microsoft, or ibm.

                                                    Still big companies, lots of smart people, but nothing above norm.

                                                    • nsib96 3 hours ago

                                                      Which companies would you look up to nowadays? Genuinely curious

                                                      • yhavin 2 hours ago

                                                        Deserves its own Ask HN.

                                                    • afdbcreid 8 hours ago

                                                      Here's a tip most Rust users don't know about extension traits: if you put `#[rust_analyzer::prefer_underscore_import]` above your trait (and you're using rust-analyzer and not RustRover), autocompletion and the import assist will import the trait `as _` by default, which is very useful for extension traits.

                                                      • tcallred 11 hours ago

                                                        I really appreciate that they distinguish between library code and application code. Rust gets too much of a bad rap for its complicated generic code, but in most application scenarios you are not writing code nearly that complex or generic.

                                                        • JoeDohn 12 hours ago

                                                          This is nice, I have been lurking on google and meta rust projects, mimicking and picking style by prompting LLMs to distill it, taking a look at fmt & clippy configs helps too.

                                                          But it wasn't as coherent and reliable from project to project like this guide. Kudos to google on this one !

                                                          • i2talics 11 hours ago

                                                            Much of this is very standard across the Rust ecosystem but it's very helpful to have it all in one place.

                                                            • petcat 12 hours ago

                                                              At this point, is anybody writing new C or C++? It seems like they are sunset languages even at the big corps.

                                                              • fasterik 12 hours ago

                                                                I'm pretty sure most big software projects (Windows, Linux, Chrome, gcc, LLVM, AAA game engines, ...) are still writing a lot of new C and C++. Pretty much everyone in the embedded world is as well.

                                                                As a solo programmer, I still prefer C and C++. In fact, as I've incorporated LLMs in to my workflow, I've been increasingly drawn toward C and its simplicity. A lot of the QoL features of C++ simply aren't needed when you're writing less code manually.

                                                                • loeg 7 hours ago

                                                                  Using LLMs to write C feels a little silly to me. (Unless you really need C.) LLMs are still imperfect; you're still going to get a lot of UB bugs like human-authored C.

                                                                  • Groxx 3 hours ago

                                                                    Particularly because so much of the code they're trained on has those flaws.

                                                                  • anthk 8 hours ago

                                                                    Chrome should be ported to Rust long ago. on Windows, half of the UI can migrate tomorrow with ease.

                                                                    • pjmlp 1 hour ago

                                                                      Windows is more likely to keep being a mix of .NET and C++ than anything else.

                                                                      Other than a few examples given in the past, the Rust adoption among WinDev doesn't seem to be really taking off like in Azure.

                                                                      Indeed C# is getting more low level coding features, and the unsafe memory model is being redone in .NET 11 for a reason.

                                                                      • boredatoms 6 hours ago

                                                                        With the ram shortage they could start by removing all the web-views that should have been native

                                                                    • npalli 11 hours ago

                                                                      Far from it. Until Rust can read C++ code seamlessly, there will be more code written in C++ than Rust for the foreseeable future. HPC, Finance, AI, Games, Databases, Hardware all continue to be written in C++.

                                                                      • simonask 9 hours ago

                                                                        Serious people in all of those industries are thinking about whether and how Rust is a fit for their needs.

                                                                        Like, I agree that C++ will be around for a long while, but the writing is on the wall.

                                                                        • loeg 7 hours ago

                                                                          I agree momentum for Rust is growing, but disagree that it is obvious the writing is on the wall for C++. Like, Java and C# didn't kill C++, either. In all likelihood, these languages will all coexist for a long, long time.

                                                                          • 20k 8 hours ago

                                                                            For game development its hard to see how Rust can really replace C++ in practice. It'll take 15 years at minimum to replace the current development ecosystem for building games

                                                                          • npalli 8 hours ago

                                                                            Strange position in 2026. If there is any writing in the wall it is this. Nobody is going to be writing Rust code from scratch given where LLMs are already now, much less in 5 years. A golden rule of software is fresh coding is a small part of the lifecycle most of it is maintenance. You may be able to get people to write Rust code (vibe code it), however a tiny minority of them will want to maintain LLM generated Rust code!! Rust will most likely be an intermediate representation - a security/formality check of sort - before converted into the appropriate heterogenous code across GPU/CPU/TPU/XPUs. Even there some other better representation will supplant it as Rust's ideas will be found too limiting. The idea that you as a programmer will sit and write Rust source code is just going to look very archaic. Thank god for LLMs for saving everyone just in time.

                                                                        • xedrac 11 hours ago

                                                                          Unfortunately for me, yes. Some companies are very risk adverse and would rather stick with the devil they know. They have no idea what they are sacrificing.

                                                                          • skohan 12 hours ago

                                                                            C/C++ is still relevant for HPC, where you want to carefully optimize memory management.

                                                                            • vlovich123 11 hours ago

                                                                              Hate to break it to you but Rust is equally capable of doing all the same memory management optimizations.

                                                                              • skohan 11 hours ago

                                                                                I mean you can, but C/C++ is way more ergonomic for dealing with memory layouts.

                                                                                • Philpax 10 hours ago

                                                                                  Is it? How so?

                                                                                  • FuckButtons 6 hours ago

                                                                                    It doesn’t have a stable abi, how could it be easier? I would argue that the vast majority of what rust gives you comes at a direct cost of precisely the ergonomics of manual memory management. It’s a tradeoff that makes sense much of the time, but it’s still very obviously a tradeoff.

                                                                                    • SkiFire13 13 minutes ago

                                                                                      > It doesn’t have a stable abi

                                                                                      No, Rust _has_ a stable ABI, it's the C ABI. It just isn't the default.

                                                                                      • vlovich123 5 hours ago

                                                                                        It’s easier in that you can cordon off the tricky parts being unsafe and define safe mechanics. Proof point: the Linux kernel using more and more rust and at once the platform support gets there more if the core memory management and what not will start getting ported too.

                                                                                        There’s also work actively ongoing to make certain constructs even easier to express more ergonomically and letting user programs implement some of the magic that’s currently restricted to the standard library

                                                                                        • skohan 1 hour ago

                                                                                          The Linux kernel has to balance security and performance concerns, security probably being primary, so it makes sense to make the tradeoff for more safety with worse ergonomics for memory management.

                                                                                          If all you care about is performance, you're going to be fighting Rust's memory model for no reason.

                                                                                      • smj-edison 4 hours ago

                                                                                        You don't have to deal with Rust's aliasing rules for &mut and &.

                                                                                • j1elo 11 hours ago

                                                                                  Today I went over a TODO comment from 2007 in a C++ codebase that is still evolving very vividly, year after year. Trust me, for well established projects C++ is there to stay.

                                                                                  • redox99 3 hours ago

                                                                                    Console/PC gaming is mostly C++ (and scripting/blueprints/etc).

                                                                                    • pjmlp 11 hours ago

                                                                                      Games, anything that depends on LLVM, GCC, CUDA, SYSCL,....

                                                                                      Ah and Rust's compiler backend dependency on LLVM and in the future GCC as well.

                                                                                      • geertj 3 hours ago

                                                                                        In a few years, Claude Mythos will be remembered as the moment C++ died. I am serious, very senior people are really scared of LLM found vulnerabilities and are pushing strongly for Rust.

                                                                                        • zelphirkalt 1 hour ago

                                                                                          In a few years probably no one will be thinking or talking of Mythos any longer, as it is just the next marketing item in the never ending chain of items to be released as the next scary thing.

                                                                                        • loeg 12 hours ago

                                                                                          Plenty of new C++ going on at my BigCorp employer.

                                                                                          • tkz1312 12 hours ago

                                                                                            I've been extracting a lot of verified C from theorem provers recently.

                                                                                            • neutronicus 12 hours ago

                                                                                              C++ seems alive and well in the defense space. The big contractors near me have tons of C++ job postings and I don't think I've seen a single one looking for Rust.

                                                                                              • tormeh 7 hours ago

                                                                                                The new drone companies seem to favor Rust more. Helsing sponsors a lot of Rust conferences and stuff. Quantum Systems has job postings for embedded Rust. For companies that don't have a lot of legacy influencing their decisions, Rust is pretty much always going to be in their software stack. The big primes will probably come around to it in a decade or so.

                                                                                                • thomashabets2 12 hours ago

                                                                                                  Do you know if the code bases are of the kind where dynamic memory (among many other features) is disallowed?

                                                                                                  • 3eb7988a1663 7 hours ago

                                                                                                    Defense industry can work around that.

                                                                                                      This sparked an interesting memory for me.  I was once working with a customer who was producing on-board software for a missile.  In my analysis of the code, I pointed out that they had a number of problems with storage leaks.  Imagine my surprise when the customers chief software engineer said "Of course it leaks".  He went on to point out that they had calculated the amount of memory the application would leak in the total possible flight time for the missile and then doubled that number.  They added this much additional memory to the hardware to "support" the leaks.  Since the missile will explode when it hits its target or at the end of its flight, the ultimate in garbage collection is performed without programmer intervention.
                                                                                                    
                                                                                                    https://devblogs.microsoft.com/oldnewthing/20180228-00/?p=98...
                                                                                                    • neutronicus 12 hours ago

                                                                                                      Some of them, probably.

                                                                                                      From the job postings, many of them seem to be physics simulations of various kinds where (in my experience) memory is allocated on the heap without a second thought. Well, there are second thoughts, but those second thoughts are about performance.

                                                                                                    • debo_ 8 hours ago

                                                                                                      C++ requires defensive programming, so I guess it fits that defense requires C++ programming.

                                                                                                    • m00dy 4 hours ago

                                                                                                      Rust is eating C/C++.

                                                                                                      • pjmlp 1 hour ago

                                                                                                        While depending on a compiler framework written in C++, the irony.

                                                                                                        • m00dy 1 hour ago

                                                                                                          We’re at a point where you can build anything in any language, and Rust is eating everything because its strict guarantees help cover the weaknesses of AI-assisted development.

                                                                                                          • pjmlp 1 hour ago

                                                                                                            One less reason to care about Rust then, I rather go straight to machine code.

                                                                                                            > Frame was created over the past month largely via Claude Code. The Assembly code in all its glory can be found on GitHub.

                                                                                                            https://www.phoronix.com/news/Frame-X11-Server-Assembly

                                                                                                            The eating everything part is only the usual hype cycle as folks update their CVs, in this fashion driven industry.

                                                                                                            Except this time around AI makes language knowledge meaningless, we can vibe code anything into any language.

                                                                                                            • m00dy 52 minutes ago

                                                                                                              Assembly, C, and C++ all fall into the unsafe category. They don’t offer the same memory-safety and concurrency checks Rust does when AI-generated code gets things wrong. Sorry, but this industry is more competitive than ever, and it’s starting to look like there’s no room for amateurs.

                                                                                                              • pjmlp 49 minutes ago

                                                                                                                You mean when AI generates Rust code full of unsafe code blocks and calls it a day, yeah.

                                                                                                                • m00dy 39 minutes ago

                                                                                                                  No, I mean Rust is the final nail in the coffin for C/C++ developers. In Darwinian terms, they’re a species that’s already hit its evolutionary peak and is now heading toward extinction.

                                                                                                                  • pjmlp 18 minutes ago

                                                                                                                    Looking forward to that LLVM rewrite into Rust then, to save Rust from being dragged into extinction.

                                                                                                                    Naturally everyone around the globe that contributes to LLVM will gladly contribute the rewritten version as well.

                                                                                                      • pornel 11 hours ago

                                                                                                        Cloudflare is all in on Rust, it's used everywhere by default, and C++ leftovers are being actively torn down.

                                                                                                        • nchie 56 minutes ago

                                                                                                          Going all in on Rust doesn't have to mean you'll rewrite everyone's firmware drivers in Rust, nor does it mean rewriting everyone's OS in Rust or rewriting the platform on which Rust is compiling.

                                                                                                          • pjmlp 1 hour ago

                                                                                                            So they will remove LLVM from rustc and throw away V8?

                                                                                                            • m00dy 1 hour ago

                                                                                                              It's just a matter of time.

                                                                                                              • pjmlp 1 hour ago

                                                                                                                Yeah, sure. Cranelift isn't making that much progress, and Google is in no hurry to RIIR V8.

                                                                                                                • m00dy 28 minutes ago

                                                                                                                  As far as I know, someone outside Google rewrote the TypeScript compiler in a week in Rust, and according to the benchmarks, it’s better than the Go version. The same thing will happen here. There’s no time to wait for Google. Someone else will do it.

                                                                                                                  • pjmlp 18 minutes ago

                                                                                                                    Yes, and the TypeScript team said, thanks but no we not taking it.

                                                                                                          • IshKebab 11 hours ago

                                                                                                            Yes mine is, because they have a huge amount of C++ already and none of it is publicly accessible so security isn't a concern. (Obviously there are many other reasons to prefer Rust, but that is a big one.)

                                                                                                          • oddCopper65 12 hours ago

                                                                                                            The enum-over-bool rule is the one I'd keep even solo, saved me a reversed flag in a cert validator once.

                                                                                                            • sebastianconcpt 12 hours ago

                                                                                                              This is a sub-case of the general one that is narrowing the interpretation of things. A big infinite amount of things can be true or false, only one can be a Rust variant.

                                                                                                            • eviks 2 hours ago

                                                                                                              > out of automatic formatting using #[rustfmt::skip], but only in the following situations:

                                                                                                              > Manual alignment

                                                                                                              Guess, another decade before Rust robots can do columns?

                                                                                                              • wocram 3 hours ago

                                                                                                                There's something ironic with having project specific variants in a style guide.

                                                                                                                • hitekker 8 hours ago

                                                                                                                  > Don’t use async / .await in Chromium.

                                                                                                                  That's pretty direct. IIRC, the Rust for Linux people also have that refrain informally

                                                                                                                  • slaymaker1907 11 hours ago

                                                                                                                    I have a huge disagreement here. You should absolutely be using Arc and Rc for any references *that live outside of the call stack.*

                                                                                                                    Don't do weird crap with lifetimes to try and convince the compiler that what you're doing is ok, just throw Rc/Arc on it and be done with it.

                                                                                                                    The Rc/Arc advice also applies to C++ IMO, though you use different constructs, std::shared obviously, but there is a strong argument to be made for a std::shared_st or something which is single threaded.

                                                                                                                    It would not surprise me if this advice comes from experience with C++ where there is no Rc so reference counting is very expensive. Even so, you can greatly reduce the expense by passing things by ref where lifetimes are simple which is the vast majority of the time.

                                                                                                                    • i2talics 11 hours ago

                                                                                                                      I think using refcounting can allow you to get lazy with your object graphs, throwing referencing to objects around everywhere and then losing the ability to conceptualize who owns what and who is responsible for who (so to speak). Sticking to a stricter ownership graph forces you to be more deliberate with how your types are designed and this can lead to better architecture in the long run.

                                                                                                                      • mrbonner 8 hours ago

                                                                                                                        Agree. I think for the limited scopes such as in a mod/function, using Rust's borrow checker semantic makes sense as it is easier to fit in our mental model. If you have to pass those data structures around to the outside of your limited scopes, I would prefer Rc/ARc more. I also think the style guide has a catch all phrase there when it says "OK to use Rc/ARc depending on the complexity...". For me, having to pass a shared reference around is enough complexity to reason about.

                                                                                                                        • wtetzner 10 hours ago

                                                                                                                          I find using lifetimes to be simpler and easier to follow than reference counting, unless you're in a situation where you actually need a shared lifetime.

                                                                                                                          Adding Rc/Arc is just another layer of indirection and noise that makes the code hard to read.

                                                                                                                        • incrediblers 11 hours ago

                                                                                                                          Getters and setters is the one I'm most at disagreement with.

                                                                                                                             // Mine
                                                                                                                             let label = Label.text("Hello Wold");
                                                                                                                             let label_text = label.get_text();
                                                                                                                          
                                                                                                                             // Theirs
                                                                                                                             let label = Label.set_text("Hello Wold");
                                                                                                                             let label_text = label.text();
                                                                                                                          
                                                                                                                          A method is a way to accomplish a specific task. Emphasis on specific not generic. The getter task is to always return. The setter task is specific. So the method should be the setter - `text`, `color`, `fill`. In Rust the getter can't have same name, so prefix it. Not the other way around.
                                                                                                                          • i2talics 11 hours ago

                                                                                                                            Their style is pervasive in Rust, such as in the standard library, so I would personally apply a when-in-rome philosophy. FWIW something like `.text("hello")` I would expect to see in a builder-pattern but not in a setter for an object that's already built.

                                                                                                                            That being said I don't particularly understand your conception of a method. They are both methods. The getter ought to have a shorter name since it is probably called more frequently and because it inherently has less of an impact -- this goes along with the principle that names that demand attention should be larger and easier to notice.

                                                                                                                            • incrediblers 11 hours ago

                                                                                                                              My use case is a TUI framework (https://www.incredible.rs/). The setters configure elements in a chain-able manner. I grappled with the rust convention and decided to go the other way. Rational as mentioned.

                                                                                                                              But this made me think...

                                                                                                                              > "The getter ought to have a shorter name since it is probably called more frequently"

                                                                                                                              So i checked. Rough agent driven counts:

                                                                                                                              https://github.com/ronilan/incredible-flappy 407 setters and 183 getters.

                                                                                                                              https://github.com/ronilan/rusticon 546 setters and 5 getters

                                                                                                                              https://github.com/ronilan/shape-sorting 688 setters and 33 getters.

                                                                                                                              And in a code editor with a lot of ui configurations based on reusable elements 2865 setters and 206 getters.

                                                                                                                              In reactive apps on state handlers call on setters with state values. No getters involved...

                                                                                                                              • afdbcreid 11 hours ago

                                                                                                                                That means those are probably builders and not setters. Do they change an existing object or a newly-constructed or to-be-constructed object?

                                                                                                                                • incrediblers 10 hours ago

                                                                                                                                  They are setters. They modify an element after instantiation. Mostly as part of the initial build, but then also in the event closure. Under the hood, a struct with interiorly mutable fields.

                                                                                                                                  • i2talics 5 hours ago

                                                                                                                                    This sounds a lot like a builder but the line can be blurry. For a Rust stdlib example, the `process::Command` type is considered a builder even though it is not named "CommandBuilder", and the final operation is spawning a subprocess, not returning some other data.

                                                                                                                                    • incrediblers 3 hours ago

                                                                                                                                      What I was saying is that I think a "flipped pattern" where anything that sets something sometime somewhere is the word and anything that reads is a get_* makes this fine distinction unnecessary... and that makes life easier... I came to Rust from JS where one can overload methods... I understand from other comments that the set_* convention may have arrived from C++... In any case, consistency I think beats specifics.

                                                                                                                                    • fwip 8 hours ago

                                                                                                                                      Gotcha, so in your case, users of the library will set values much more often than read them (since the reading will be done by the TUI framework for display).

                                                                                                                              • trimbo 11 hours ago

                                                                                                                                This style is aligned with protocol buffers, which is aligned with the style of protos in C++.

                                                                                                                                https://protobuf.dev/reference/rust/rust-generated/

                                                                                                                                • epage 11 hours ago

                                                                                                                                  I think which to use in general Rust code depends on the purpose of your type.

                                                                                                                                  A builder type like `Command` will have unqualified setters and `get_` qualified getters.

                                                                                                                                  For record-like-structs, I think unqualified getters becomes preferred and `set_` qualified setters.

                                                                                                                                • manlymuppet 6 hours ago

                                                                                                                                  How useful would this be to simply feed to an LLM and say to follow strictly?

                                                                                                                                  • threethirtytwo 6 hours ago

                                                                                                                                    Not useful at all. It uses up context. You need all the context you can get for the LLM read the code later for you later.

                                                                                                                                    • JimTheMan 6 hours ago

                                                                                                                                      Could you just get a separate agent to do a pass over existing code and make conform? Like super linting.

                                                                                                                                      Not a professional programmer, so it's a genuine question rather than a statement.

                                                                                                                                      • threethirtytwo 4 hours ago

                                                                                                                                        Sure you can do that. But what’s the practical point if only your agent is reading it? Your agent doesn’t care about linting.

                                                                                                                                  • mmooss 10 hours ago

                                                                                                                                    > Usage of lowercase alphabets in hex literals (0xab123cdef as opposed to 0xAB123CDEF): hex_literal_case = Lower

                                                                                                                                    Anytime numbers and letters are mixed, it's more readable if the letters are lowercase. It's easier to read the variable heights - numbers are usually capital letter height, sometimes with descenders - and avoids confusing 0O, I1, even 8B and 5S (think of a degraded printed serial number, poor lighting, etc.). There's only l problem that persists.

                                                                                                                                    • IX-103 9 hours ago

                                                                                                                                      OT, but it was interesting. Some old typewriters didn't have a separate 1 a lower case L key. They had keys for the other numbers, but you were expected to just type a lower case L for 1.

                                                                                                                                    • younglunaman 11 hours ago

                                                                                                                                      ctrl+c > ctrl+v > into my AGENTS.md for my next rust project /s

                                                                                                                                      • xiaodai 9 hours ago

                                                                                                                                        why is google using github, a Micro$oft product?

                                                                                                                                        • shaftway 9 hours ago

                                                                                                                                          I 100% guarantee that this source of truth for this is either in google3 or git-on-borg and is being mirrored to GitHub for external use. There aren't a lot of public catch-all repos or public micro repos published by Google. Given that, GitHub is a reasonable choice.

                                                                                                                                        • holografix 11 hours ago

                                                                                                                                          Things like this make me appreciate Gofmt so much

                                                                                                                                          • japgolly 5 hours ago

                                                                                                                                            But there's a rustfmt already. Anyway, the style guide is larger in scope than just code formatting.

                                                                                                                                          • Thanemate 12 hours ago

                                                                                                                                            Not trying to rain on someone's parade but, the only reason why would care about style guides nowadays is to feed them to our model of choice and let it do what it's supposed to be doing.

                                                                                                                                            So it's not like I am willing to read through this and think to myself "I cannot wait to pick up some new ways of doing things". I'm the general to my agentic army now.

                                                                                                                                            I guess you would code manually every now and then for your own enjoyment but at that point do you care about style guides written for scale?

                                                                                                                                            • nimih 12 hours ago

                                                                                                                                              I'm not sure I really agree with your main point (I think it's probably still important for LLM-generated code to be generally human-understandable, at least if you care about long-term maintainability), but setting that aside to answer this question:

                                                                                                                                              > I guess you would code manually every now and then for your own enjoyment but at that point do you care about style guides written for scale?

                                                                                                                                              I think they're still quite valuable in that case, for a couple reasons:

                                                                                                                                              - When learning a new language (which happens much more frequently when writing code "for pleasure," as it were), "written for scale" guidelines still translate pretty well to "written for oneself" IME. At the very least, they tell you what to expect in code you read, and give you a reasonable starting point as you develop your own taste and stylistic preferences.

                                                                                                                                              - I've noticed some open source projects beginning to institute anti-AI contribution guidelines, and such projects still benefit from codified style guides. Google obviously doesn't fall under this category themselves, but in other language ecosystems, their style guides tend to find use in OSS projects.

                                                                                                                                              • anonymous908213 12 hours ago

                                                                                                                                                > I'm the general to my agentic army now.

                                                                                                                                                What have you produced with your agentic army? Would you like to share with the class?

                                                                                                                                                • bigfishrunning 12 hours ago

                                                                                                                                                  my guess is a lot of heat, some water vapor....

                                                                                                                                                  • solyin 11 hours ago

                                                                                                                                                    Why would they when the class is full of dropouts who, generously, have a 0 percent chance of going "hey, y'know what, that's actually kinda cool! I'm going to change my mind about LLMs being useless" and a 100% chance of going "ur project is total shit and you should feel bad".

                                                                                                                                                    • nvme0n1p1 11 hours ago

                                                                                                                                                      The people you call "dropouts" have written 100% of the software that people actually use and actually keeps the real world running, so maybe you shouldn't write them off.

                                                                                                                                                      • lioeters 6 hours ago

                                                                                                                                                        The "all in on LLM" hypesters are as obnoxious as the "all in on Rust" hipsters.

                                                                                                                                                        We get it, Rust is great, and LLMs too. But sometimes it's like listening to teenage philosophers who just discovered atheism, who go on and on to disparage all religions every chance they get. They're so full of themselves that they don't realize they're missing entire areas of understanding about the world and people.

                                                                                                                                                        The juvenile arrogance on display in many threads in recent years is second-hand embarrassing. Meanwhile the greybeards continue getting the job done, with or without LLMs, in Rust, C++ or even C.

                                                                                                                                                        • solyin 3 hours ago

                                                                                                                                                          Class is full of dropouts != every single last member of the class is a dropout.

                                                                                                                                                          • scottyah 10 hours ago

                                                                                                                                                            Unlike Linus, Jeff Dean, DHH, John Carmack, Guido van Rossum? I really want to know who you think writes "100% of the software that people actually use and actually keeps the real world running"

                                                                                                                                                            • nvme0n1p1 9 hours ago

                                                                                                                                                              Have any of those people (excluding DHH) said anything even half as ridiculous as "I'm the general to my agentic army now"? Or are they adults using tools where they make sense and avoiding them where they don't?

                                                                                                                                                              If you think style guides don't matter anymore, I encourage you to submit patches to the people on your list whose credibility you're borrowing, and see if they agree. Tell Linus to delete https://docs.kernel.org/process/coding-style.html because it doesn't matter because we have AI now. Or ask GvR if the current Python maintainers should deprecate https://peps.python.org/pep-0008/, since agents don't need it.

                                                                                                                                                              • vor_ 7 hours ago

                                                                                                                                                                Linus doesn't even do much programming by his own admission. He's a release manager.

                                                                                                                                                                • japgolly 5 hours ago

                                                                                                                                                                  That being said there was a story about him debugging an issue recently with some pretty serious help from AI.

                                                                                                                                                                • Mawr 9 hours ago

                                                                                                                                                                  Hmm, one of those is not like the others...

                                                                                                                                                          • smoe 12 hours ago

                                                                                                                                                            First paragraph: “includes guidance on API and implementation design”

                                                                                                                                                            It seems to me that if the intent is not just to produce code but also to operate it, having the different pieces behave in a similar, predictable way is kind of nice. Whether the software is written by AI or humans.

                                                                                                                                                            • u1hcw9nx 12 hours ago

                                                                                                                                                              Not trying to rain on someone's parade, but the only reason I would care about HN comments nowadays is to feed them to my model of choice and let it generate the contrarian hot takes it's supposed to be generating. So it's not like I am willing to read through this thread and think to myself "I cannot wait to pick up some new ways of complaining about documentation." I'm the Editor-in-Chief to my synthetic pundit army now.

                                                                                                                                                              I guess you would type out a comment manually every now and then for your own enjoyment, but at that point do you really care about comments at scale?

                                                                                                                                                              ---

                                                                                                                                                              EDIT (above is a joke) It's very important that every time you find something that is of no use to you, you write a comment explaining that this link is of no interest to you, discouraging people from things you have no interest in. Monoculture for all!

                                                                                                                                                              • yodsanklai 12 hours ago

                                                                                                                                                                This is what we do in my company, give the guidelines to the model. Unfortunately, the model isn't always following them and it's impossible to enforce them manually. There's too much code to review, the code is generally low quality, and is more often than not auto-approved by AI.

                                                                                                                                                                Unless you're working on your own project on which you have full control, or you have a strong authority figure in your company who cares about that, it's a lost battle.

                                                                                                                                                                It's sad for anyone who love their craft, but tbh I'm not even sure it matters anymore for most projects.

                                                                                                                                                                • scottyah 10 hours ago

                                                                                                                                                                  Either you can put it in a linter and automate/force it, or people/agents will take liberties. I feel like there's usually exceptions where a well-meaning guideline doesn't properly fit a specific scenario.

                                                                                                                                                                • monocasa 12 hours ago

                                                                                                                                                                  The point of style guides is to optimize for readability despite a cognitively diverse workforce coding in the same repos.

                                                                                                                                                                  I would think they're probably even more meaningful in an agentic world.

                                                                                                                                                                  Shitty generals can't review meaningfully review the work of their troops.

                                                                                                                                                                  On top of that all, I just enjoy programming itself. It's less and less of the meat of a software job over time, but I was coding before I got paid for it, and I'll probably keep coding well after I can get paid for it.

                                                                                                                                                                  • mkagenius 12 hours ago

                                                                                                                                                                    > Shitty generals can't review meaningfully review the work of their troops.

                                                                                                                                                                    Except that reviewing has become just asking your agent what that piece of code does in english. Reading code has a bit of cognitive load, that we will probably drop it in coming years

                                                                                                                                                                  • petersellers 12 hours ago

                                                                                                                                                                    Are you saying that you don't ever look at the code once it's been generated?

                                                                                                                                                                    • bigstrat2003 11 hours ago

                                                                                                                                                                      AI bros think you can never look at code and make good software. They're wrong, of course, but they refuse to listen and will probably never listen until the shoddy quality of their work becomes too great to paper over.

                                                                                                                                                                      • IX-103 9 hours ago

                                                                                                                                                                        If you set up a really good AI code review pipeline then you can get pretty close. I've heard a couple of tech companies are targeting 80% of changes not needing human review and they'll probably scale up from there.

                                                                                                                                                                        • bigstrat2003 14 minutes ago

                                                                                                                                                                          If you aren't reviewing 100% of the code, you aren't doing engineering, you're producing slop.

                                                                                                                                                                    • gatlin 12 hours ago

                                                                                                                                                                      Seems very much like your goal was to rain on a parade.