You could look at Lisp. It's kind of the opposite of Go in this regard. You can use whatever paradigm you like, generate new code on the fly, use types or leave them. It even allows you to easily extend the language to your taste, all the way down to how code is read.
But Lisp might violate your set of absolutes.
I see an effect where the languages whose primary goal is a particular set language design choices (such as strict memory safety over all else) grow a cult following that enforces said design choices. Maybe in the pursuit of an opinionated language, even if the designers are reasonable at the language's inception, the community throws out logic and "opinionated" becomes a in-group out-group tribal caveman situation.
I think you've got this backward. It's not that the particular choices are important. It's a thing happening on a higher meta level than that.
Some programming languages are, by design intent, "living" languages, evolving over time, with features coming and going as the audience for the language changes.
"Living" languages are like cities: the population changes over time; and with that change, their needs can shift; and they expect the language to respond with shifts of its own. (For example: modern COBOL is an object-oriented language. It shifted to meet shifting needs of a new generation of programmers!)
If you were able to plot the different releases of a living language in an N-dimensional "language-design configuration space", these releases would appear to arbitrarily jump around the space.
Other languages, though, are, by their design intent, "crystallized" languages — with each component or feature of the language seeing ever-finer refinement into a state of (what the language maintainers consider) perfection; where any component that has been "perfected" sees no further work done, save for bugfixes. For such languages, creating a language in this way was always the designers' and maintainers' goal — even before they necessarily knew what they were creating.
"Crystallized" languages are like paintings: there was an initial top-down rough vision for the language (a sketch); and at some early point, most parts of the design were open for some degree of change, when paint was first being applied to canvas. But as the details were filled in in particular areas, those areas became set, even varnished over.
If you plot the successive releases of a crystallized language in design configuration space, the releases would appear to converge upon a specific point in the space.
The goal with a crystallized language is to explore the design space to discover some interesting point, and then to tune into that interesting point exactly — to "perfect" the language as an expression of that interesting concept. Every version of the language since the first one has been an attempt to find, and then hit, that point in design space. And once that point in design space is reached, the language is "done": the maintainers can go home, their jobs complete. Once a painting says what it "should" say, you can stop painting it!
If a crystallized language is small, it can achieve this state of being entirely "finished", its spec set in stone, no further "core maintainer" work needed. Some small crystallized languages are even finished the moment they start. Lua is a good example. (As are most esolangs — although they're kind of a separate thing, being created purely for the sake of "art", rather than sitting at the intersection of "work of art" and "useful tool" as crystallized languages do.)
But large crystallized languages do exist. They seek the same fate as small crystallized languages — to be "finished" and set in stone, the maintainers' job complete. They just rarely get there, because of how large a project it is to refine a language design.
You might intuitively associate a "living" language with democratic control, and a "crystallized" language with a Benevolent Dictator For Life (BDFL) figure with an artistic vision for the language. But this is not necessarily true. Python was a "living" language even when it had a BDFL. And Golang is a "crystallized" language despite its post-1.0 evolution being (essentially) directed by committee.
---
The friction you're describing, comes from developers who are used to living languages, trying to apply the same thinking about "a language changing to serve the needs of its users" to a crystallized language.
Crystallized languages do not exist primarily to serve their users. They exist to be expressions of specific points in design space, quintessences of specific concepts. Those points in design space likely are useful (esolangs excluded); but the expectation is that people who don't find that point in design space useful, should choose a different language (i.e. a different point in design space) that's more suited to their needs, rather than attempting to shift the language's position in design space.
Adding a bridge is a sensible proposal for a city. You can get entire streets of buildings torn down to make way for the bridge, if the need is there. But adding a bridge is not not a sensible proposal for a (mostly-finished) painting. If you want "this painting but with a bridge in it", that's a different painting, and you should seek out that painting. Or paint it yourself. Or paint the bridge on some kind of transparent overlay layer, and hang that overlay in front of the painting.
Conveniently for this discussion, Borgo here is exactly an example of a language that's "someone else's painting, but now with the bridge I wanted painted on an overlay in front of it." :)
True.
> We could probably argue for all eternity about code formatting, for instance. But Go went and set it in stone.
This is part of the story that Rob Pikes uses to justify how opinionated Go is, but it's a bit stupid given that most language do fine and I've never seen any debates about the code formatting after the very beginning of a project (where it's always settled quickly in the few case where it happens in the first place).
The real reason why Go is opinionated is much more mundane: Rob is an old man who think he has seen it all and that the younger folks are children, and as a result he is very opinionated. (remember his argument against syntax coloring because “it's for babies” or something).
It's not bad to be opinionated when designing a language, it give some kind of coherence to it (looking at you Java and C++) but it can also get into the way of users sometimes. Fortunately Go isn't just Rob anymore and isn't impervious to changes, and there is finally generics and a package manager in the language!
For those who want to feel the wind of coding freedom blow through their hair, I can recommend to spend some time learning Lisp. It offers the most freedom you can possibly have in a programming language. It might enlighten you in many other ways. It won't be the last language you learn, but it might be the most fruitful experience.
The thing is that Common Lisp has most of what current programming languages are trying to implement. But it does require learning proper programming and being a good engineer.
Are there online examples? Can you point to someone's blog where they are proselytizing regarding Common Lisp, but it's obvious they don't have experience in it (perhaps betrayed by technical problems in their rhetoric).
Firstly, Ken Thompson is a master at filtering out unnecessary complexities and I highly rate his opinion of the important and unimportant things.
Secondly, the Go team were never against generics, the three early designers agreed the language needed generics but they couldn't figure out a way to add it orthogonally.
Go has gone on to be very successful in cloud and networked applications (which it was designed to cater for), which lends credit to the practicalities of what the designers thought as important, HN sentiments notwithstanding.
This is a PR statement that has been introduced only after Go generics landed, for years generics were dubbed “unnecessary complexity” in user code (Go has had generics from the beginning but only for internal use of the standard library).
> Go has gone on to be very successful in cloud and networked applications (which it was designed to cater for), which lends credit to the practicalities of what the designers thought as important
Well, given that the k8s team inside Google developed their own Go dialect with pre-processing to get access to generics, it seems that its limitations proved harmful enough.
The main reason why Go has been successful in back-end code is the same as the reason why any given language thrive in certain environments: it's a social phenomenon. Node.js has been even more successful despite JavaScript being a far from perfect language (especially in the ES 5 era where Node was born), which shows that you cannot credit success to particular qualities of the language.
I have nothing against Go, it's a tool that does its job fairly well and has very interesting qualities (fast compile time, self-contained binaries, decent performance out of the box), but the religious worship of “simplicity” is really annoying. Especially so when it comes in a discussion about error handling, where Go is by far the language which makes it the most painful because it lacks the syntactic sugar that would make the error as return value bearable (in fact the Go team was in favor of adding it roughly at the same time as generics, but the “simplicity at all cost” religion they had fostered among their users turned back against them and they had to cancel it…).
Nodejs has been more successful than Go in cloud?
Yes, that's what's called an ecosystem effect. But k8s has been the biggest open source codebase for a while, so it's far from insignificant.
> you should consider whether the team was trying to code more with Java idioms than with Go ones.
Turns out generics, the “Java idiom” in question, was eventually added to Go after many years, so maybe it was in fact useful and it's not just k8s devs who where idiots following “java idioms”…
> Nodejs has been more successful than Go in cloud?
Nodejs has been more successful than Go in pretty much everything except in orchestration tools (because of the ecosystem effect mentioned above) which is a tiny niche anyway. Go is a very small language on terms of use compared to Nodejs, or PHP, which are arguably language with a terrible design.
Typical Gate keeping the gate keepers of simplicity and pretty sure you code 23.5 hours a day on Haskell
I've no idea what you mean, you should keep your argumentation simpler ;)
I have never done any real programming in Java itself, but the parts of Java world that I learned while writing some Clojure circa 2015 felt pretty coherent. Now I'm curious what I missed.
No, they don't. Most languages turn dealing with code formatting, into an externality foisted upon either:
• the release managers (who have to set up automation to enforce a house style — but first have to resolve interminable arguments about what the given project's house style should be, which creates a disincentive to doing this automation); or
• the people reviewing code in the language.
In most languages, in a repo without formatting automation, reviewers are often passed these stupid messy PRs that intermingle actual semantic changes, with (often tons of) random formatting touch-ups — usually on just the files touched by the submitter's IDE.
There's a constant chant by code reviewers to "submit formatting fixes as their own PR if there are any needed" — but nobody ever does it.
Golang 1. fixes in place a single "house style", removing the speedbump in the way of automating formatting; and 2. pushes the costs of formatting back to the developer, by making most major formatting problems (e.g. unneeded imports) into compile-time errors — and also, building a formatter into the toolchain where it can be relied upon to be present and so used in pre-commit hooks, guaranteeing that the code in the repo never gets out of sync with proper formatting.
"Getting in the way of the users" is the right thing to do, when "the users" (developers) fan in 1000:1 with code reviewers and release managers, who have to handle any sloppiness they produce.
(Coincidentally, this is analogous to other Google thinking about scaling compute tasks. Paraphrasing: "don't push CPU-bottlenecked workloads from O(N) mostly-idle clients, out to O(log N) servers. Especially if the clients are just going to sit there waiting for the servers' response. Get as much of the compute done on the clients as possible; there's not only far more capacity there, but blocking on the client blocks only the person doing the heavy task, rather than creating a QoS problem." Also known as: "the best 'build server' is your own workstation. We gave you a machine with an i9 in it for a reason!")
Actual response:
• For dev-time iteration, you want local builds; for large software (e.g. Chrome), you make this work by making builds incremental. So it takes a few hours to build locally the first time you build, but then it's down to 30s to rebuild after a change.
• But for building releases, you can't rely on incremental builds; incremental builds (i.e. building on top of a cache from previous arbitrary builds) would be non-deterministic and give you non-reproducible builds, exactly what a release manager doesn't want. So releases, at least, are stuck needing to "build the world." You want to accelerate those — remote build infra is the way to go. Remote, distributed build infra, ideally (think: ccache on Flume.)
These remote/distributed builds do still cohere to the philosophy in the abstract, though — a remote build is not the same as a CI build, after all; the dev's own workstation is still acting as the planner and director of the build process.
> incremental builds (i.e. building on top of a cache from previous arbitrary builds) would be non-deterministic and give you non-reproducible builds
Isn’t this exactly what Bazel solves?
Bazel doesn't go full Nix — it doesn't capture the entire OS + build toolchain inside its content-fingerprinting to track it for changes between builds. It's more like Homebrew's build env — a temporary sandbox prefix containing a checkout of your project, plus symlinks to resolved versions of any referenced libs.
Because of this, you might build, upgrade an OS package referenced in your build or containing parts of your toolchain, and then build again, Bazel (used on its own) doesn't know that anything's different. But now you have a build that doesn't look quite like it would if you had built everything with the newest version of the package.
I'm not saying you can't get deterministic builds from Bazel; you just have to do things outside of Bazel to guarantee that. Bazel gets you maybe 80% of the way there. Running the builds inside a known fixed builder image (that you then publish) would be one way to get the other 20%.
I have a feeling that Blaze is probably better for this, though, given all the inherent corollary technologies (e.g. objFS) it has within Google that don't exist out here.
Really, they do: there a millions of us coding in those other languages just fine, and automatic formatting has been a thing for decade, and I'm not aware of a single language out there that doesn't have such a formatting tool.
The only exception with Go is that you cannot change the default settings. But that's it. In any other language you can use a code formatter with the default settings and the “speedbump in the way of automating formatting” you talk about doesn't exist anywhere but in your mind.
> where it can be relied upon to be present and so used in pre-commit hooks
You know that a failing git hook aborts the commit? So that with any language, if the formatter isn't installed in the machine, the commit cannot be performed, which means that the formatter can actually be relied upon anyway. In practice, the hardest part is making sure people all have the git hook installed (that's not that hard but that's the hardest part).
As I said before, Go has many useful properties, but automatic formatting is definitely not what makes Go relevant, and the endless stream of Gophers who argue this are just ridiculing themselves in front of everybody else.
When making a trivial fix PR to an upstream FOSS project, if I find that a missing third-party linter install has force-rejected my commit (that I know has correct syntax)... then I just give up on making that PR. I can't be assed to install some random linter. (Third-party linters have a history of being horrible to install†.)
Small amounts of friction can be enough to shape behavior (see https://en.wikipedia.org/wiki/Nudge_theory.) Aggregated over a large project's entire community, this can make an appreciable difference in code quality over time.
† Mind you, a linter that exists as a library dev dependency of the project is fine, too. I had to pull the deps to build and run the tests, so the linter will be there by the time I attempt to commit. It's just linters that are their whole own projects that give me a jaw-ache.
> and the endless stream of Gophers who argue this are just ridiculing themselves in front of everybody else.
I don't even use Go! I mainly write Elixir, actually. Which also has a built-in auto-formatter.
To me, the nice thing about the formatter being built into Elixir (and of-a-piece with the compiler), is that when I use macros, the purely-in-memory generated-and-compiled code can be inspected in the REPL, and shows as formatted (because it passes through the auto-formatter), rather than looking like AST gunk. Without having had to pay that auto-formatting cost at compile time (because that would also be a cost you'd pay at runtime codegen time, which you might do a lot of if you've built a domain-specific JIT on top of the macro system.)
As a result, almost all Go code out there is formatted the exact same way and nobody has ever had to have the dreaded code formatting discussion about Go at their company. Eliminating such bikeshedding for every user of the language is a solid win.
That's why all the languages proceeding Go have adopted the same approach, e.g. Rust and Zig. Python's Black formatter has been directly inspired by gofmt as well.
What is provided by default really matters.
You can format on save or in a pre commit hook. But that the language has a single canonical format makes it kind of new.
A simple settings file set in stone by the CTO, such a hard task to do.
The fact that is even a novelty unaware of, only confirms the target group for the language.
It does seem hard thing to do. Working over dozens of enterprise shops in last 15 years I have not see such setting done or dictated at all. So whole codebase used to be mishmash of person styles.
Then again, any such CTO is likely also going to be someone who tends to think about things like "the ability to hire developers already familiar with the language to reduce ramp-up time" — and will thus end up picking a common and low-expressivity opinionated language. Which usually just means Java. (Although Golang is gaining more popularity here as well, as more coding schools train people in it.)
And then you have a 100 companies with 100 CTOs resulting in 100 different styles.
With Go there is only one style everywhere.
Which will have a different style you need to contend with.
But with Go every single sane piece of code you find will be formatted with gofmt and will look mostly the same.
Not having exceptions (but then having them anyway through panic, but whatever) is a choice - but the other reasonable alternative is the Maybe monad. What Go did is not reasonable. I might be okay if they had been working on getting monads in, but they haven't.
I have a specific hatred for Go because it seems perfectly suited to make me hate programming: it has some really good ideas like fast compile time speeds, being able to cross-compile on any platform and being a systems language without headers.
But then I try to write code in it and so. much. boilerplate.
If boilerplate is cause for you to dislike the language, fine.
But your unnecessarily strong language "Go is opinionated and it's opinion is wrong", "What Go did is not reasonable", "I have a specific hatred for Go" speaks more about you than Go.
Go's choice of trade-off much was practical and reasonable, engineering-wise.
Your opinion is entirely wrong.
That said, suggesting adding exceptions to Go is about as reasonable as adding a GC to Zig. How much effort would you spend arguing against someone bringing that up as a serious proposal?
Suggesting the addition of exceptions to Go is as reasonable as suggesting the addition of loops to Rust. Which is to say that it already has exceptions, and always has. Much of the language's design is heavily dependent on the presence of exceptions.
Idioms dictate that you probably shouldn't use exceptions for errors (nor should you in any language, to be fair), but even that's not strictly adhered to. encoding/json in the standard library famously propagates errors using the exception handlers.
The only error-related concept the Go language has is the error type, but it comes with no handling semantics. Which stands to reason as there is nothing special about errors. Originally, Go didn't even have an error type, but it was added as a workaround to deal with the language not supporting cyclic imports.
Your pedantry is hilarious and contradictory.
Basically, discussions have context and I have no intention of prepending 10 disclaimers to every statement I make to preemptively guard against people interpreting my comments as absolutes in a vacuum.
But, if you'd kindly come back to the topic at hand:
> That is what the discussion here is about - the way errors are handled in a language in practice, not in theory.
While I'm not entirely convinced that is accurate, I will accept it. Now, how does:
- "That said, suggesting adding exceptions to Go is about as reasonable as adding a GC to Zig."
Relate to that assertion? What does "suggesting adding exceptions to Go" have to do with a common pattern that has emerged?
"spherical cow in a vacuum"
I only learned about this recently. Very funny to me, and appropriately used here. Ref: https://en.wikipedia.org/wiki/Spherical_cow func Must[Value any](v Value, err error) Value {
if err != nil {
panic(err)
}
return v
}
Must(strconv.Atoi("not a number"))
(https://go.dev/play/p/NnrZ30TflDI);)
You think wrong. Go preaches that zero values should be useful, with means in the common (T, error) scenario, T should always be useful even if there is also an error state. Worst case, you will get the zero value in return, which is still useful. This means that the caller should not need to think about the error unless it is somehow significant to the specific problem they face. They are not dependent variables.
I understand where you are coming from as in other languages it would be catastrophic to ignore errors, but that's not how Go is designed. You cannot think of it like you do other languages, for better or worse.
I disagree with this blanket assertion. In a limited set of cases would I ever expect a result to be valid if there was also an error.
Also, when you disagree with what someone thinks, there are different ways to respond and using "You think wrong" is probably one of the most confrontational ways of responding.
You have to return something for T. Go does not allow you to return nothing. Why would you return garbage when you can just as easily return the zero value, that of which should always be useful? Yes, you technically could return garbage, but why? There is absolutely no justification. Consider,
func GetUser() (*User, error) {
return nil, ErrNotFound
}
Here, T is useful. You don't necessarily need to look at error in this example. You can meaningfully work with T alone if the error state is insignificant to your specific use case.What's the alternative?
func GetUser() (*User, error) {
return &User{
Name: "No User",
Email: "not@found.com",
Role: DoesNotExist,
}, ErrNotFound
}
Why on earth would you do that?> Also, when you disagree with what someone thinks, there are different ways to respond and using "You think wrong" is probably one of the most confrontational ways of responding.
Imagine thinking that the output of software is being confrontational or exhibiting of any kind of output that congers this kind of change in "emotional state". As nonsensical as the random number generator outputting three consecutive 6s and then concluding that it must be the work of the devil. So strange.
Just because exception and error both start with the letter "e" does not mean they are in any way related. They have very different meanings and purposes.
For those who do not know: .NET is cross platform, MS has official documentation on how to deploy it in Docker, and it is MIT licensed.
And if you want to deploy a backend for your webapp the tersenes can now rival Flask - plus the compiler can cross compile it to any supported platform, even in a form that works without .NET installed.
And of course it has Jetbrains support through Rider.
It has its flaws, but the latest version (Scala 3) is really really good. The community is open to different styles of programming - from using it as a "better Java" to "pure functional programming like in Haskell".
Hilariously I was using a gen AI (phind) and asked it to generate some scala code and it no joke suggested the code in both implematic scala and in java style, and all you had to do is look at it and you could see java style was 1000X easier to read/maintain.
On the other hand, if you carefully select your team or work alone, then this is not a problem at all.
Btw, there isn't really "one" idiomatic scala style - therefore I tend to believe that you are not familiar with the language and the community.
That is their point. There's too many styles.
As opposed to an expressive language with powerful macros. Another person could hop on the team and write something that only makes sense to them, and now you have to understand their half-baked DSL.
The burden is on you, in an expressive language, to have a style guide for your team or enforce a style through code reviews. Whereas Golang just has that built-in and obviously is more than capable for writing production software.\
This is a criticism often levied against Scala because you can do pretty much any paradigm in it, and there's lots of disagreements over when to do what paradigm.
It is rather the non-believers in exception handling who are the lunatic fringe that benefits from a healthy dose of ostracism.
func try(fn func()) { fn() }
func catch(fn func(any)) {
if v := recover(); v != nil {
fn(v)
}
}
func throw(v any) { panic(v) }
func fail() {
throw("Bad things have happened")
}
func main() {
try(func() {
defer catch(func(v any) {
fmt.Println(v)
})
fail()
})
}
Sorry.The API reference doesn't state that panics are a part of the expected error interface, and the source code references seem to be using panics as a way to validate invariants. Is that what you're referring to?
I'm not entirely sure if the panics are _just_ for sanity, or if input truly can cause a panic. If it's the latter, then I agree - yikes.
[1] - https://pkg.go.dev/encoding/json
[2] - https://cs.opensource.google/search?q=panic&sq=&ss=go%2Fgo:s...
The syscall/js package [0] throws panics if something goes wrong, rather than returning errors.
Go already has try/catch exceptions. We just don't use them most of the time because they're a really bad way of handling errors.
if err != nil {
return err
}
repeated all over the place, is the epitome of productivity!In JS, for example, people don‘t even know which functions could throw exceptions, and just ignore them, most of the time. Fast to write and looks nice, but is horrible quality and a nightmare to debug.
If you do naked if-err-return-err, you are likely doing error handling wrong.
Plenty of The Go Way arguments apply to software we were writing from the dawn of computing until the 1990's, and there are plenty of reasons why, with exception of Go (pun intended), the industry has moved beyond that.
In our Go codebases, the error reporting and subsequent debugging and bug fixing is night and day from our Python, Perl, Ruby, PHP, Javascript, and Elixir experiences.
The one glaring case where this is untrue is in our usage of Helm which, having been written in Go, I would expect better error handling. Instead we get, "you have an error on line 1; good luck" - and, inspired, I looked at their code just now. Littered with empty if-err-return-err blocks - tossing out all that beautiful context, much like an exception would, but worse.
https://github.com/search?q=repo%3Ahelm%2Fhelm%20%20if%20err...
I can't speak for all Go users, but what I have seen is that the feature set in Go lends itself to code that handles errors, and exceptions simply don't -- I can say this because I've worked in a dozen different production systems for each of perl, python, js, elixir, and php -- I'm left believing that those languages _encourage_ bad error handling. Elixir is way cool with pattern matching and I still find myself wishing for more Go-like behavior (largely due to the lacking type system, which I hear they are working to improve).
I've not used Rust which apparently is the golden standard in the HN sphere
There's bad programmers everywhere. Writing if err != nil { return err } is the same as not handling exceptions (they just bubble up).
Maybe you think this because go shoves the exceptions front and center in your face and forces you to deal with them. I suppose it can be a helpful crutch for beginners but it just winds up being annoying imo.
But in fact, there probably exists a minority of developers who somehow had Go foisted upon them, and who would would like it to have basic features like exceptions.
Why do you think so? Maybe I'm an odd case, but my main use case for enums is for APIs and database designs, where I want to lock down some field to a set of acceptable values and make sure anything else is a mistake. Or for state machines. Error handling is manageable without enums (but I love Option/Result types more than Go's error approach, especially with the ? operator).
Then what you are really looking for is sum types (what Rust calls enums, but unusually so), not enums. Go does not have sum types, but you can use interfaces to archive a rough facsimile and most certainly to satisfy your specific expectation:
type Hot struct{}
func (Hot) temp() {}
type Cold struct{}
func (Cold) temp() {}
type Temperature interface {
temp()
}
func SetThermostat(temperature Temperature) {
switch temperature.(type) {
case Hot:
fmt.Println("Hot")
case Cold:
fmt.Println("Cold")
}
}If the humans choose to make an exception for that, it can be done. Granted, the planning that has taken place thus far has rejected such an exception, but there is nothing about Go that fundamentally prevents carving out an exception.
They can certainly help solve some of the same problems. Does that make them related? I don't know.
By definition, an enumeration is something that counts one-by-one. In other words, as is used in programming languages, a construct that numbers a set of named constants. Indeed you can solve the problem using that:
type Temperature int
const (
Hot Temperature = iota
Cold
)
func SetThermostat(temperature Temperature) {
switch temperature {
case Hot:
fmt.Println("Hot")
case Cold:
fmt.Println("Cold")
}
}
But, while a handy convenience (especially if the set is large!), you don't even need enums. You can number the constants by hand to the exact same effect: type Temperature int
const (
Hot Temperature = 0
Cold Temperature = 1
)
func SetThermostat(temperature Temperature) {
switch temperature {
case Hot:
fmt.Println("Hot")
case Cold:
fmt.Println("Cold")
}
}
I'm not sure that exhibits any sum type properties. I guess you could see the value as being a tag, but there is no union. const (
Hot Temperature = 0
Cold Temperature = 1
)
Isn't really a good workaround when lacking an enumeration type. The compiler can't complain when you use a value that isn't in the list of enumerations. The compiler can't warn you when your switch statement doesn't handle one of the cases.Refactoring is harder - when you add a new value to the enum, you can't easily find all those places that may require logic changes to handle the new value.
Enums are a big thing I miss when writing Go, compared to when writing C.
Enumeration isn't a type, it's a numbering construct. Literally, by dictionary definition. Granted, if you use the Rust definition of enum then it is a type, but that's because it refers to what we in this thread call sum types. Rust doesn't support "true" enums at all.
> The compiler can't complain when you use a value that isn't in the list of enumerations.
Well, of course. But that's not a property of enums. That's a property of value constraints. If Go supported value constraints, then it could. Consider:
type Temperature 0..1
const (
Hot Temperature = 0
Cold Temperature = 1
)
Then the compiler would complain. Go lacks this in general. You also cannot define, say, an Email type: type Email "{string}@{string}"
Which, indeed, is a nice feature in other languages, but outside of what enums are for. These are separate concepts, even if they can be utilized together.> Enums are a big thing I miss when writing Go, compared to when writing C.
Go has enums. They are demonstrated in the earlier comment. The compiler doesn't attempt to perform any static analysis on the use of the use of the enumerated values because, due to not having value constraints, "improper" use is not a fatal state[1] and Go doesn't subscribe to warnings, but all the information you need to perform such analysis is there. You are probably already using other static analysis tools to assist your development. Go has a great set of tools in that space. Why not add an enum checker to your toolbox?
[1] Just like it isn't in C. You will notice this compiles just fine:
typedef enum {
Hot,
Cold
} Temperature;
void setThermostat(Temperature temperature) {
switch (temperature) {
case Hot:
printf("Hot\n");
}
}
int main() {
setThermostat(10);
}No, it isn't, unlike C, in which it is. The C compiler can actually differentiate between an enum with one name and an enum with a different name.
There's no real reason the compiler vendor can't add in warnings when you pass in `myenum_one_t` instead of `myenum_two_t`. They may not be detecting it now, but it's possible to do so because nothing in the C standard says that any enum must be swappable for a different enum.
IOW, the compiler can distinguish between `myenum_one_t` and `myenum_two_t` because there is a type name for those.
Go is different: an integer is an integer, no matter what symbol it is assigned to. The compiler, now and in the future, can not distinguish between the value `10` and `MyConstValue`.
> Just like it isn't in C. You will notice this compiles just fine:
Actually, it doesn't compile "just fine". It warns you: https://www.godbolt.org/z/bn5ffbWKs
That's about as far as you can get from "compiling just fine" without getting to "doesn't compile at all".
And the reason it is able to warn you is because the compiler can detect that you're mixing one `0` value with a different `0` value. And it can detect that, while both are `0`, they're not what the programmer intended, because an enum in C carries with it type information. It's not simply an integer.
It warns you when you pass incorrect enums, even if the two enums you are mixing have identical values. See https://www.godbolt.org/z/eT861ThhE ?
Go on. Given:
type E int
const (
A E = iota
B
C
)
enum E {
A,
B,
C
}
What is missing in the first case that wouldn't allow you to perform such static analysis? It has a keyword to identify initialization of an enumerated set (iota), it has an associated type (E) to identify what the enum values are applied to, and it has rules for defining the remaining items in the enumerated set (each subsequent constant inherits the next enum element).That's all C gives you. It provides nothing more. They are exactly the same (syntax aside).
> It warns you
Warnings are not fatal. It compiles just fine. The Go compiler doesn't give warnings of any sort, so naturally it won't do such analysis. But, again, you can use static analysis tools to the same effect. You are probably already using other static analysis tools as there are many other things that are even more useful to be warned about, so why not here as well?
> enum in C carries with it type information.
Just as they do in Go. That's not a property of enums in and of themselves, but there is, indeed, an associated type in both cases. Of course there is. There has to be.
Type information. The only type info the compiler has is "integer".
> It has a keyword to identify initialization of an enumerated set (iota),
That's not a type.
> it has an associated type (E)
It still only has the one piece of type information, namely "integer".
> and it has rules for defining the remaining items in the enumerated set
That's not type information
> That's all C gives you.
No. C enums have additional information, namely, which other integers that type is compatible with. The compiler can tell the difference between `enum daysOfWeek` and `enum monthsOfYear`.
Go doesn't store this difference - `Monday` is no different in type than `January`.
> Warnings are not fatal.
Maybe, but the warning tells you that they types are not compatible. The fact that the compiler tells you that the types are not compatible means that the compiler knows that the types are not compatible, which means that the compiler regards each of those types as separate types.
Of course you can redirect the warning to /dev/null with a flag, but that doesn't make the fact that the compiler considers them to be different types go away.
Whether you like it or not, C compilers can tell the difference between `Monday` and `January` enums. Go can't tell the difference between `Monday` and `January` constants. How can it?
Nobody said it was. Reaching already? As before, enums are not a type, they are a numbering mechanism. Literally. There is an associated type in which to hold the numbers, but that's not the enum itself. This is true in both C and Go, along with every other language with enums under the sun.
> The compiler can tell the difference between `enum daysOfWeek` and `enum monthsOfYear`.
Sure, just as in Go:
type Day int
const (
Monday Day = iota
Tuesday
// ...
)
type Month int
const (
January Month = iota
February
// ...
)
func month(m Month) {}
func main() {
month(January) // OK
month(Monday) // Compiler error
}
> Go doesn't store this difference - `Monday` is no different in type than `January`.Are you, perhaps, mixing up Go with Javascript?
> How can it?
By, uh, using its type system...? A novel concept, I know.
Rust enums are as you describe, as they accidentally renamed what was historically known as sum types to enums. To be fair, Swift did the same thing, but later acknowledged the mistake. The Rust community doubled down on the mistake for some reason, now gaslighting anyone who tries to use enum in the traditional sense.
At the end of the day it is all just 1s and 0s. If you squint hard enough, all programming features end up looking the same. They are similar in that respect, but that's about where the similarities end.
Then wrap appropriately. Something like sqlc will actually generate everything you need.
The thing is, these don't add much on their own. You'd have to bring in pattern matching and/or a bunch of other things* that would significantly complicate the language.
For example, with what's currently in the language, you could definitely have an option type. You'd just be limited to roughly an api that's `func (o Option[T]) IsEmpty() bool` and `func (o Option[T]) Get() T`. And these would just check if the underlying point is nil and dereference it. You can already do that with pointers. Errors/Result are similar.
A `try` keyword that expands `x := try thingThatProducesErr()` to:
x, err := thingThatProducesErr()
if err != nil {
return {zero values of the rest of the function signature}, err
}
Might be more useful in go (you could have a similar one for pointers).* at the very least generic methods for flat map shenanigans
Just need to make sure the Option exposes the internal value only through:
func (o Option[Value]) Get() (Value, bool) {
return o.value, o.exists
}
Accessing the value is then forced to look like this: if value, ok := option.Get(); ok {
// value is valid
}
// value is invalid
Thus, there's no possibility of an accidental nil pointer dereference, which I think is a big win.A Result type would bring a similar benefit of fixing the few edge cases where an error may accidentally not be handled. Although I don't think it'd be worth the cost of switching over.
if value != nil {
// value is valid
}
// value is invalid
?Of course, this is often left out, but you can just as easily do:
value, _ := option.Get()
So this is just not true:> Using an Option instead of a pointer buys you the inability to forget to check for nil.
> Of course, this is often left out, but you can just as easily do:
Unfortunately it gets brought up pretty much every time in these discussions.
Deliberate attempts to circumvent safety are not part of the threat model. The goal is prevention of accidental mistakes. Nothing can ultimately stop you from disabling all safeties, pointing the shotgun at your foot and pulling the trigger.
type Option1 struct { ... }
type Option2 struct { ... }
type MyEnum interface { Option1 | Option2 }
var myValue MyEnum // currently not legal Go
That doesn't solve all the use cases for enums / sum types, but it would be useful.What people want "the ability to express enums with an associated value", I think we should invent a new term.
With that I mean fundamental and fool proof functions for to/from a string, to/from an int, exhaustive switch cases, pattern matching, enumerating.
Seems like something that wouldn’t be too hard but everybody always fails on something.
There's not much you can do with an enumeration. It's just something that counts one-by-one.
A useful tool when you have a large set of constants that you want to number, without having to manually sit there 0, 1, 2, 3... But that's the extent of what it can offer.
> With that I mean fundamental and fool proof functions for to/from a string, to/from an int, exhaustive switch cases, pattern matching, enumerating.
While a programming language may expose this kind of functionality, none of these are properties of enums. They are completely separate features. Which you recognize, given that you are able to refer to them by name. Calling these enums is like calling if statements functions because if statements may be layered with functions.
type E int
const (
A E = iota
B
C
)
It's funny how people who have clearly never even looked at Go continually think they are experts in it. What causes this strange phenomena?They can have values like sum types, or not.
It does not. You'll notice that if you read through your link. A tag-only union is not the same thing, even if you can find some passing similarities.
If you mean it has enums like the Democratic People's Republic of Korea has a democracy, then sure, it does have enums in that sense. I'm not sure that gives us anything meaningful, though.
If we're being honest, sum types are the better solution. Enums are hack for type systems that are too limited for anything else. They are not a feature you would add if you already have a sufficient type system. It's not clear why Rust even wants to associate itself with the hack that are enums, but your link shows that its author has a fundamental misunderstanding of what enums even are, so it may be down to that.
To be fair, Swift made the same mistake, but later acknowledged it. It is interesting that Rust has chosen to double down instead.
Why not? Seems to function the same way.
Realistically, there isn't a whole lot of practical difference. They were both created to try and solve much the same problem. As before, I posit that there is no need for a language to have both. You can do math on enum values, but that is of dubious benefit. In theory, tag-only unions provide type safety, whereas enums are just values so there is no inherit safety... But, as you probably immediately recognized a few comments back, with some static analysis you can take the greater view,
type E int
const (
A E = iota
B
C
)
and invent something that is just as useful as proper type safety. All the information you need is there. So, in reality, that need not even be significant.But, technically there is a difference. Values and types are not the same thing.
Source? Is this something that is widely accepted, or just how you think enums should be defined.
My understanding is you are saying (using c++ as an example since it has both types) an `enum` is a "true" enum, while an `enum class` somehow isn't?
To which language?
> `enum` is a "true" enum, while an `enum class` somehow isn't?
No. Enums are used in both cases. The difference there is in the types the enums are applied to. In one case, a basic integer-based type. In the other, a class.
This differs from Rust. Rust does not use enums. It relies on the type itself to carry all the information. C++ enum classes could have done the same, so it is not clear why they chose to use enums, but perhaps for the sake of familiarity or backwards compatibility with the regular enum directive?
I mean more in the sense of "where did you get this definition from."
> The difference there is in the types the enums are applied to. In one case, a basic integer-based type. In the other, a class.
I'm still not seeing a difference, mainly because when I went to see how c++'s `enum class` and rust's `enum`, they both seemed to work the same.
#[repr(u8)]
enum Words {
Foo = 0,
Bar,
Baz,
}
const _: () = {
assert!(Words::Foo as u8 == 0);
assert!(Words::Bar as u8 == 1);
assert!(Words::Baz as u8 == 2);
};
vs enum class Words : uint8_t {
Foo = 0,
Bar,
Baz
};
static_assert(static_cast<uint8_t>(Words::Foo) == 0);
static_assert(static_cast<uint8_t>(Words::Bar) == 1);
static_assert(static_cast<uint8_t>(Words::Baz) == 2);In other words, you want to have a conversation with someone else by proxy? If that's the case, why not just go talk the other people you'd really prefer to talk to?
> I'm still not seeing a difference
There is no difference. I recant what I said. This (strangely, undocumented in the above link) functionality does, in fact, provide use of enums.
Curious addition to the language. Especially when you consider how unsafe enums are. When would you ever use it? It is at least somewhat understandable in C++ as it may be helpful to "drop down" to work with the standard enum construct in some migratory situations, but when do you use it in Rust?
sorry, I didn't mean to be so argumentative or negative. (The "You'll have to ask the Rust community. Rust lacks enums." did get me a little annoyed :p)
> This (strangely, undocumented in the above link) functionality does, in fact, provide the use of enums.
That link was from "the rust book" which is primarily is for learning rust. For more technical info the referenced is used https://doc.rust-lang.org/reference/items/enumerations.html
> When would you ever use it?
I assume (like you said for c++) a good reason would be for c/c++ interoperate, but it also probably makes things like serialization easier. Sometimes you just need a number (e.g. indexing an array) and it's simpler to be able to cast then have a function that goes from enum -> int.
> Especially when you consider how unsafe enums are.
Do note though, going from int -> enum is an unsafe op which would require `std::mem::transmute`.
Thanks, but I had no reason to think that the output of software has human qualities.
> That link was from "the rust book" which is primarily is for learning rust.
Learn Rust by keeping features of the language a secret? Intriguing.
> a good reason would be for c/c++ interoperate
I'm not sure that's a good reason. C++ doing it is questionable to begin with, but at least you can understand how a bad idea might have made it in many years ago when we didn't know any better.
> it also probably makes things like serialization easier.
It would, except you would never want to serialize the product of an enum as it means your program becomes forever dependent on the structure of the code. I mean, sure, you can remove the enum later if you are to change the code, so you're not truly stuck, but that kind of defeats the purpose. You may as well do it right the first time.
Enums are inherently unsafe. That you have to be explicit about converting the union to an integer at least gives some indication that you are doing something unsafe. It is not so unusual that Rust allows some kind of "escape hatch" to get at the actual memory. What is interesting, though, is that it also allows manipulation of what values are assigned by the enumerator as a first-class feature, which suggests that it promotes this unsafe behaviour. This is what is surprising and what doesn't seem to serve a purpose.
So when I looked at Go for the first time, the error handling was one of the many positive features.
Is there any good reason for wanting try/catch other than being lazy?
sounds good on paper, but seeing "if err!=nil" repeated million times in golang codebases does not create positive impression at all
Rust's error handling is clearly better than Go's, but Go's is better than exceptions and the complaints about verbosity are largely complaints about having to actually consider errors.
I'm honestly asking as someone neutral in this, what is the difference? What is the difference between building out a stack trace yourself by handling errors manually, and just using exceptions?
I have not seen anyone provide a practical reason that you get any more information from Golangs error handling than you do from an exception. It seems like exceptions provide the best of both worlds, where you can be as specific or as general as you want, whereas Golang forces you to be specific every time.
I don't see the point of being forced to deal with an "invalid sql" error. I want the route to error out in that case because it shouldn't even make it to prod. Then I fix the SQL and will never have that error in that route again.
With exception style code the overwhelming temptation will be to call `string_to_int()` and forget that it might throw an exception.
Cut to your app crashing when someone types an invalid number.
Now, you can handle errors like this properly with exceptions, and checked exceptions are used sometimes. But generally it's extremely tedious and verbose (even more than in Go!) and people don't bother.
There's also the fact that stack traces are not proper error messages. Ordinary users don't understand them. I don't want to have to debug your code when something goes wrong. People generally disabled them entirely on web services (Go's main target) due to security fears.
Is it? In my experience it's very short, especially considering you can catch multiple errors. Do my users really need a different error message for "invalid sql" vs "sql connection timeout?" They don't need to know any of that.
> There's also the fact that stack traces are not proper error messages
I would say there's not a proper error message to derive from explicitly handling sql errors. Certainly not a different message per error. I would rather capture all of it and say something like "Something went wrong while accessing the database. Contact an admin." Then log the stack trace for devs
Yes! A connection timeout means it might work if they try again later. Invalid SQL means it's not going to fix itself.
But in any case, the error messages are probably the minor part. The bigger issue is about properly handling errors and not just crashing the whole program / endpoint handler when something goes wrong.
> I would say there's not a proper error message to derive from explicitly handling sql errors. Certainly not a different message per error. I would rather capture all of it and say something like "Something went wrong while accessing the database. Contact an admin." Then log the stack trace for devs
Ugh these are the worst errors. Think about the best possible action that the user could take for different failure modes.
"Contact an admin" is pretty much always bottom of the list because it rarely works. More likely options are "try again later", "try different inputs", "clear caches and cookies", "Google a more specific error".
Giving up on making an error message because you only have a stack trace and don't want to show it means users can't pick between those actions.
If you have written a "something went wrong" error I literally hate you.
You're totally misunderstanding what I'm saying. If I have an error the user can act on, I'll make that error message for them. If they can't act on it, I will make a generic catcher and ask them to contact an admin because that's the only thing they can do. It is not my experience that any of these things you've written (try again later, try a different input) are applicable when an error comes up in my apps. It's always an unexpected bug a developer needs to fix, because we've already handled the other error paths. And the bug is not from "not explicitly handling the error."
> Think about the best possible action that the user could take for different failure modes.
What if contacting an admin IS the best possible action? Which is what I'm referring to.
In the case of invalid sql, your route should crash because it's broken. Or catch it and stop it. It's functionally the same thing.
You seem to be under the impression that having exceptions mean people can't handle errors explicitly? It just prevents the plumbing of manually bubbling up the error. It means you can do so MORE granularly. Also, there are some errors that are functionally the same whether you handle them explicitly or not. There are unexpected errors, and even Golang won't save you from that. Golang doesn't even care if you handle an error. It will compile fine. Even PHP will tell you if you haven't handled an exception.
> If you have written a "something went wrong" error I literally hate you.
Lol.
Not at all! It's possible, but it's very tedious, and the lazy "catch it in main" option is so easy that in practice when you look at code that uses exceptions people actually don't handle errors explicitly.
> It means you can do so MORE granularly.
Again, it doesn't just mean that you can; it means that you will. And for proper production software that's not a good thing.
> There are unexpected errors
Only in languages with exceptions. In a language like Rust there are no unexpected errors; you have to handle errors or the compiler will shout at you.
But again, handling an error doesn't necessarily prevent bugs. Just because you handled an error doesn't mean the error won't happen in Prod. It just means when it does, you wrote a message for it or custom behavior. Which could be good, or it might be functionally as effective as returning a stack traces message. It depends on the situation.
For what it's worth, I've never seen people not handle errors that the user could do anything with. If it's relevant to the user, we handle it.
It absolutely does. Checked exceptions sort of half get there too but they are quite rarely used (I think they are used in Android quite well). They were actually removed from C++ because literally nobody used them.
> handling an error doesn't necessarily prevent bugs.
I never made that claim.
> I've never seen people not handle errors that the user could do anything with.
We already talked about "something went wrong" messages. Surely you have seen one of those?
My point is that "something went wrong" messages are for errors the user CANT and SHOULDNT do anything with.
What? Of course there is. Rust added panic! exactly because unexpected errors are quite possible.
Unexpected errors, or exceptions as they are conventionally known, are a condition that arises when the programmer made a mistake. Rust does not have a complete type system. Mistakes that only show up at runtime absolutely can be made.
You cannot force your dependencies to hand you a stack trace with every error. But in languages that use exceptions a stack trace can be provided for "free" -- not free in runtime cost, but certainly free in development cost.
Golang code has a rhythm: you do the thing, you check the error, you do the thing, you check the error. After a while it becomes automatic and easy to read, like any other syntax/formatting. You notice if the error isn't checked.
Yes, at first it's jarring. But to be honest, the jarring thing is because Go code checks the error every time it does something, not because of the actual "if err != nil" syntax.
I've gotten used to Javas getter/setter spam, does that make it a good idea?
Moreover, don't you think that something like Rusts ? operator wouldn't be a perfect solution for handling the MOST common type of error handling, aka not handling it, just returning it up the stack?
val, err := doAThing()
if err != nil {
return nil, err
}
VERSUS val := doAThing()?I'd be very surprised if, in Rust codebases, there's not an implicit bias against wrapping and towards using `?`, just to help keep things "clean"; which has implications not only for debugging, but also for situations where doing something more is required for correctness.
I see two issues with the `?` operator:
1. Most Go code doesn't actually do
return nil, err
but rather return nil, fmt.Errorf("opening file %s as user %s: %w", file, user, err)
that is, the error gets annotated with useful context.What takes less effort to type, `?` or the annotated line above?
This could probably be solved by enforcing that a `?` be followed by an annotation:
val := doAThing()?("opening file %s as user %s: %w", file, user, err)
...but I'm not sure we're gaining much at that point.2. A question mark is a single character and therefore can be easy to miss whereas a three line if statement can't.
Moreover, because in practice Go code has enforced formatting, you can reliably find every return path from a function by visually scanning the beginning of each line for the return statement. A `?` may very well be hiding 70 columns to the right.
1. Most often found in library code, the error types have the metadata embedded in them so they can nicely be bubbled up the stack. That's where you'll find `do_a_thing().map_err(|e| Error::FileOpenError { file, user, e })?`, or perhaps a whole `match` block.
2. In application code, where matching the actual error is not paramount, but getting good messages to an user is; solutions like anyhow are widely used, and allow to trivially add context to a result: `do_a_thing().context("opening file")?`. Or for formatted contexts (sadly too verbose for my taste): `do_a_thing().with_context(|| format!("opening file {file} as user {user}"))?`. This will automatically carry the whole context stack and print it when the error is stringified.
Overall, what I like about this approach is the common case is terse and short and does not hinder readability, and easily gives the option for more details.
As for the second point, what I like about _not_ easily seeing all return paths (which are a /\? away in vim anyways), is that special handling stands out way more when reading the file. When all of the sudden you have a match block on a result, you know it's important.
I'm a huge fan of keeping things simple; my experience has shown me that complex things have lots of obscure failure points, while simple things are generally more robust.
> More terse is not the same as more readable (in fact, I find the reverse).
I generally agree, but I also find that "all explicit" also hinders readability because it tends to drown the nitty-gritty details. As always it's a matter of balance :) And I think that neither go nor rust are great in this matter as one is verbose and the other falls in the "keyword soup" with the chain call, the closure, and the format macro. I'm pretty sure something in between could be found.
Okay, but other than exceptions, whats the alternative?
Of course, this is also scarily non-explicit.
I only briefly tried Rust and was turned off by the poor ergonomics; I don't think (i.e. open to correction) that the Rust way (using '?') is a 1:1 replacement for the use-cases covered by Go error management or exceptions.
Sometimes (like in the code I wrote about 60m ago), you want both the result as well as the error, like "Here's the list of files you recursively searched for, plus the last error that occurred". Depending on the error, the caller may decide to use the returned value (or not).
Other times you want an easy way to ignore the error, because a nil result gets checked anyway two lines down: Even when an error occurs, I don't necessarily want to stop or return immediately. It's annoying to the user to have 30 errors in their input, and only find out about #2 after #1 is fixed, and #3 after #2 is fixed ... and number #30 after #29 is fixed.
Go allows these two very useful use-cases for errors. I agree it's not perfect, but with code-folding on by default, I literally don't even see the `if err != nil` blocks.
Somewhat related: In my current toy language[1], I'm playing around with the idea of "NULL-safety" meaning "Results in a runtime-warning and a no-op", not "Results in a panic" and not "cannot be represented at all in a program"[2].
This lets a function record multiple errors at runtime before returning a stack of errors, rather than stack-tracing, segfaulting or returning on the first error.
[1] Everyone is designing their own best language, right? :-) I've been at this now since 2016 for my current toy language.
[2] I consider this to be pointless: every type needs to indicate lack of a value, because in the real world, the lack of a value is a common, regular and expected occurrence[3]. Using an empty value to indicate the lack of a value is almost certainly going to result in an error down the line.
[3] Which is where there are so many common ways of handling lack of a value: For PODs, it's quite popular to pick a sentinel value, such as `(size_t)-1`, to indicate this. For composite objects, a common practice is for the programmer to check one or two fields within the object to determine if it is a valid object or not. For references NULL/null/nil/etc is used. I don't like any of those options.
It is a 1:1 replacement.
I think you're thinking of the case when you have many results, and you want to deal with that array of results in various ways.
> Result implements FromIterator so that a vector of results (Vec<Result<T, E>>) can be turned into a result with a vector (Result<Vec<T>, E>). Once an Result::Err is found, the iteration will terminate.
This is one such way, but there are others - https://doc.rust-lang.org/rust-by-example/error/iter_result....
This doesn't handle every case out there, but it does handle the majority of them. If you'd like to do something more bespoke, that's an option as well.
This may be a crazy/dumb take, but would it be so wrong to allow code outside the function to take the wheel and do a return? Then you could define common return scenarios and make succinct calls to them. Use `returnif(err)` for the most typical, boilerplate replacement, or more elaborate handlers as needed.
The main benefits of a Result type are brevity and the inability to accidentally not handle an error.
A funny drawback of the current Go design that a Result type would solve is the need to return zero values of all the declared function return types along with the error: https://github.com/golang/go/issues/21182.
That may be superficially true but don’t forget our brain is structured to optimize every repetitive work or some boilerplates, we can basically use “strcpy” and “string_copy” we are so used to all these that even if repeated a billion times it can be processed fast
In a hot path it’s often beneficial to not have lots of branches for error handling. Exceptions make it cheap on success (yeah, no branches!) and pretty expensive on failure (stack unwinding). It is context specific but I think that can be seen as a good reason to have try catch.
Now of course in practice people throw exceptions all the time. But in a tight, well controlled environment I can see them as being useful.
This is true but the branch isn't taken unless there's an error in Go.
Given that the Go compiler emits the equivalent of `if (__unlikely(err != nil)) {...}` and that any modern CPUs are decently good at branch prediction (especially in a hot path that repeats), I find it hard to believe that the cost would be greater than exceptions.
Because fundamentally the function you called can return different errors at any point so if you just propagate the error the code paths are in fact not spelled out at all because the function one above in the hierarchy has to deal with all the possible errors two calls down which are not transparent at all.
There's no requirement for the calling function to handle each possible type of error of the callee. It can, as long as the callee properly wrapped the error, but it's relatively rare for that to be required. Usually the exact error is not important, just that there was one, so it gets handled generically.
EDIT
Inspired by this comment: https://news.ycombinator.com/item?id=40220147
I forgot about exception stack traces, including "chained" exceptions. These are incredibly powerful when writing enterprise software that commonly has a stack 50+ levels deep.
Error returns are no different, assuming a proper implementation like the Result type in Rust. The difference is, unhandled error returns are found at compile time but unhandled exceptions only show up at runtime, when it's too late.
> Another point this is overlooked in these discussions: Exceptions and error codes can, and do, peacefully co-exist.
Both Go and Rust have panics, which are basically exceptions that are generally not supposed to be caught. They are used for unrecoverable cases like running out of memory or programmer mistakes. There's otherwise no reason to mix the two.
> Another thing about exceptions, especially in enterprise programming, you can add a human readable error message. That is not possible when only returning error codes.
I don't really know what you mean, it's equally possible in both cases. If anything, the error return implementation that Go uses is probably the most optimal out there when it comes to error messages. Most look like:
return nil, fmt.Errorf("opening file %s as user %s: %w", file, user, err)
Whereas most exception code will just dump a stacktrace since that's the default.You generally need to skip all lines that the exception invalidates. That's why it's a block or conditional.
It's the best strategy for short running programs, or scripts if you will. You just write code without thinking about error handling at all. If anything goes wrong at runtime, the program aborts with a stacktrace, which is exactly you want and you get it for free.
For long-running programs you want reliability, which implies the need to think about and explicitly handle each possible error condition, making exceptions a subpar choice.
1. err != nil, nondefault return value
2. err != nil, default return value
3. err == nil, nondefault return value
4. err == nil, default return value
when often what you want to express only has two: either you return an error and there's no meaningful output, or there's output and no error. A type system with tuples but no sum types can only express "and", not "or".
Try/catch is super confusing because the catch is often far away from the try. And in Python I just put try/catch around big chunks of code just in case for production.
I think Go is more stable and readable because they force you not to use the lazy unreadable way of error handling.
Enums I honestly never used in Go also not the not-type-safe ones.
But I'm also someone who used interfaces in Go maybe I think 4 times only in years and years of development.
I just never really need all those fancy things.
For example, and option type with enums combined can ensure return values are checked by providing a compile time error if a case is missing (as expressed in the first few examples of the readme).
But they decided not to add enums because it conflicted and overlapped too much with interfaces.
I just want to add "my" experience that personally, yes maybe you can argue enums are nice, but I never missed them in Go.
I personally agree with the Go team on how they argue and for me it would be a step back if they listened to the herd that does not take all sides of the story into consideration but just keeps pushing enums.
Try/catch is just a really bad thing all "hacky solution" alarm bells go off for me if you want to change error handling to giant try/catch blocks.
I'm very curious now about how it might conflict and/or overlap with interfaces.
To reach the goal of an enumeration type (and all the strong type-checking that that brings with it), enums could look as simple as:
type DayNames enum {
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
}
...
func isFunDay (dow DayNames) {
// This must fail to compile, because there is an unhandled enumeration
switch {
case Sunday: ...
case Monday: ...
case Tuesday: ...
case Thursday: ...
case Friday: ...
case Saturday: ...
}
...
}
...
isFunDay (0) // Compile failure
var x int
isFunDay (x) // Compile failure
And I don't see how that conflicts or overlaps with interfaces.Here you Go: https://go.dev/doc/faq#variant_types
Hah :-)
> Here you Go: https://go.dev/doc/faq#variant_types
Not quite the same: Variants are a constrained list of types. Enums are a constrained list of values.
Let's assume that I agree with the reasoning for not having a constrained list of types.
It still doesn't tell me why we can't have a constrained list of values.
However, 2 things I would be enthusiastic about if it got included in the language: - having ‘?’ As syntactic sugar for ‘if(err != nil) …’. Would make code more easily readable, and I think that is a benefit for programmers trying to keep things simple. - Sum Types. I’ve had a few cases where this would’ve been very useful. I consider the ‘var state customtype = iota’ a bit too easy to make mistakes with (eg exhaustive checking of options).
Like generics, I hope that when that happens, they take a very deliberate approach on doing it.
But you ruined it with "fancy things" which shows offhand disregard and disrespect.
A question like "what do you need these features for?" would have been a better contribution to the forum.
I also wanted to add that I used inheritance only ONCE in all my years of writing Python in all other millions of lines of code inheritance was not the best solution.
This is my daily struggle as a CTO. People using waaayy too many "fancy" features of languages making it totally unreadable and unmaintainable.
It's their ego they want to show off how many complex language features they know. And it's ruining my codebases.
Not sure why you are conflating both. Also inheritance was known to be the wrong tool for the job at least 15 years ago, maybe even 20. Back then people wrote Java books that said "prefer composition over inheritance" so your analogy didn't really land.
Everyone who uses sum types in production code agrees they reduce bugs.
Maybe it's time for you to retire.
> This is my daily struggle as a CTO
This is a nice humblebrag. Why does it matter that you are a CTO for this comment? It doesn't. It would better written as: "This is my daily struggle with my team."