334 points · by rom16384 · 7y ago · 214 comments
- performance & high concurrency - a small language feature set so I can hire & train awesome programmers with a different background - practical solutions, with a focus on getting things done
I feel confident that with Go 2 they will continue to go down this road. The `try` syntax looks kinda confusing with the implicit return. On the other hand, nothing too crazy.
And Go obviously doesn't prioritize performance as much as C++ or Rust. Case in point is with very same error handling proposal discussed here. You're going to have to pay a performance price for using a handler since the Go compiler not only avoids inlining defer blocks (if I understand correctly), but even allocates dynamic memory for each block. Meanwhile, equivalent RAII in C++ has no overhead over manual code.
Yes, the Go compiler team is now working on working on fixing this issue, but defer is not a new language construct and they should have started fixing that long ago, considered how often it's being used. What's worse, they still didn't make it a stated goal to eliminate the overhead of using defer completely, but only talk about reducing overhead in common cases.
This approach makes me sad, because Go does have the engineering power and stated design goals to be more serious about performance. Yeah, I feel confident Go will keep improving, but just the same as Java does (without the same hype).
[1] Although until recently they did have radically different choices about which kind of performance to optimize, e.g. Java went up with throughput (Throughput-optimized, JIT tricks for fastest execution after warmup), while Go went for low worst-case latency and faster startup time.
If performance is your main requirement, at the expense of everything else, then Go is definitely not a good choice.
Many consider it a good compromies between performance, readability, syntax, ecosystem, concurrency support etc..., and I believe it is what their designers aimed for originally.
And I'm not saying that other languages do not offer similar compromises, it's nice to have options.
I don't think anyone is claiming that Go will outperform well-optimized C++, if you're willing to write your server software in it.
Of the languages you mentioned Java would be the most typically considered alternative for server software. You mentioned Go's low latency but there's also some other strengths like more control of memory layout, slices make it easy to avoid copying in APIs, Goroutines can be lighter weight than Java threads, etc. But as long as Go is roughly comparable I think it's fair to consider Go performant, since Java itself is one of the most mature and optimized languages for server software.
I've always assumed that the compile time comparisons were made against C++ since Google had a lot of large systems written in C++ that they said took a long, long time to compile.
Today I think C# using .NET Core is a good general language. It is easy to learn, fast and compilles pretty fast. It also handles concurrency with async/await or threads. It still has longer start up time than Go, like Java, and might use a bit more memory but should work for most systems.
Anyway, cherrypicking a single feature of Go and claiming it's an example of why Go doesn't care about performance feels unfair. There's definitely been a huge amount of engineering effort spent on Go performance, especially latency in the GC. Defer is "slow" but it is probably rarely a bottleneck for anyone's use case. Try/catch are pretty slow in many languages.
They constantly improve defer's performance. If it's all you have against go, then I guess it's good enough for you.
I would actually feel better if the proposed generics were a little less powerful. Composing generics can get ugly. This could be countered by community norms, however.
The Zen of Rust is very much in the direction that standard operators shouldn't be more "special" than necessary, and a lot of fundamentals become "library-able" or at least library-extensible. Go simply doesn't take this approach. It's a more opinionated language, and it some cases that means you get the tool it makes for you, rather than getting to craft your own tool for yourself.
The reason they exist is because Go language designers could not do without them. The same people that have claimed for years that Go didn't need generics.
Considering all the successful software that's been written in Go, they weren't exactly wrong.
I guess the new bit is the variable-arity result from a function, not just a language feature (e.g. <- or range).
Technically ("well, acksually"), Go doesn't "lack generics". It lacks user-defined generics. The language implementation has several generics in it, you just can't add your own. So if you hear "Go doesn't have generics" that can give you a slightly incorrect impression about the language itself, but of course what people do generally mean is that it lacks user-defined generics and that that is bad, so there's still certainly a valid criticism there. It just may not quite be what you thought it was.
If we call this type of ad-hoc implementation "generics", we're going down a very deep rabbit hole, since then almost any programming language can be said to have generics. For instance, Write[Ln] in Pascal, sizeof() in C, all array functions in Java pre-1.5. In other words, technically when people say "Language X lacks generics" they always mean "Language X lacks orthogonal, predictable, non ad-hoc, user defined generics".
So there's no point in requiring the "user-defined" qualifier. For "generics" to mean anything useful, there must be some languages that the word applies to and some that it doesn't. If you treat "user-defined" as implicit, then that works. If you don't, then it says nothing.
Yes it does, generics are types. You bet all these append(T[A],A)T[A] tricks are hard-coded in the compiler in an adhoc fashion, and not part of Go's type system.
f, err := os.Open(filename)
if err != nil {
return …, err
}
is simplified to: f := try(os.Open(filename))
> I dislike the try implementationWhat would you suggest instead?
io.Reader is an example where the function can return io.EOF and still returns valid data together with a count in its first return value. If it returns a count > 0, the buffer has valid data. A lot of Go projects get this wrong because it's not obvious -- it goes against the behaviour of almost all Go functions.
Go is unfortunately full of little surprising warts like this where you have to tread super carefully. Nil channels is one of my favorites.
Down-vote if you want, but Go modules package management was handled in the same way. It's not without precedent.
Basically I agree that the process for modules may not have been ideal, but the outcome was pretty good. We could do a lot worse than getting the same again.
I think I can live with it.
I'm saying this as someone who has helped a large organization of primarily Python programmers onboard with Go. Proper error handling is already something people don't do well (until we enforced lint rules throughout the company, there were already way too many `f, _ := os.Open(...)` types of error dropping).
I'd much prefer something more strongly typed with respect to error handling, rather than less. Like if Java had disallowed extending RuntimeException so all exceptions would be part of function signatures (and therefore have to be caught).
f, err := os.Open(filename)
throw err
This allows alternate signatures easily. I also think the syntax makes a little more sense, as you're "throwing" the error up the chain unceremoniously.f := try os.Open(filename)
Or perhaps better, leaving the working code alone and concentrating on the bits people actually don't like (the error handling boilerplate).
f, err := os.Open(filename)
check(err)
There is no need to attempt to put the error handling on the same line as the function, and if you do it just gets in the way of reading the actual function call, permits nesting etc. This approach would have the advantage of leaving normal code alone and only touching the error handling.
I'd even be fine with check as a new builtin function, since it would typically sit alone anyway, I don't think it needs to be a keyword, whereas with try I think all the brackets will make it harder to read.
In fact I've just found a variant of this proposed here:
(Though I guess it's a bit harder because you'd have to have your whole team not use it...)
Implement exceptions. I'm honestly at a loss as to why the Go community hates them so much.
* Exceptions create a type of non locality that is hard to reason about.
In a language with exceptions every call to a function might result on the calling function exiting. Flow control might jump up serval stack frames unexpectedly. This works against the principles of structured programing and the normal expectation that a function when called will return a value.
This means the programer, the compiler and the runtime environment must always take this into account. This can create unexpected behaviour and creates a whole host of special cases for the compiler and runtime.
* Uncaught exceptions cause crashes
Even when the error is not something that would cause a problem if an exception isn't caught the process will crash.
* Exceptions are often too heavy for what they do.
In many situations an error is an expected/frequent outcome. Consider a disk based cache of some sort. The cache would attempt to open a file containing th cached result and if the cached result was not found then it would then do the processing to create that result.
In this case in most typical exception systems the exception would propagate up the call stack to the exception handler capturing the stack in the process. Once handler is reached all this work is thrown away.
* Exceptions create bad error messages
Too often I've seen a buggy java process spew stack traces into the logs where a single line error message saying what happened would have made the operator's 2am dealing with emergency much more manageable.
Oh, and by the way agreeing on what an exception IS brings whole another dimension into this discussion too.
So, I would go as far as "Go community hates them". People have asked for them more than once. No, we did not get them.
It doesn't encourage skipping error handling, it just allows skipping annotation where it doesn't add much. Sometimes in a chain of several calls, a function in the middle can't really add much context, and is better just to bubble the error up one level without annotation - that is what try is for.
I disagree that linters should or will recommend it except in cases where there is no annotation and there is therefore no functional difference in using try.
There is a reason Go doesn't have compiler warnings.
I don't think applicative/monadic error handling is an afterthought in any way. There are combinators to recover, for instance. But it's optimized in such a way that you can focus on the happy-path of your code and you get a sensible default for error-handling (short-circuit..just like Go's idiom!)
It achieves what a real monadic Either / Result implementation would achieve in error handling, it stays simple, and it's backwards compatible.
While I'm not a fan of Go in general, I can't help but admire at achieving all this so simply and cleanly (as much as the underlying return-two-values thing can be considered clean).
[0]: https://github.com/golang/go/issues/29934#issuecomment-48968...
One crucial difference is that the proposal uses a named `err` return value that can be manipulated in defer. This is supposed to allow cleanup and wrapping of the error type.
Rust solves wrapping is by allowing auto-conversion between error types (if they implement it).
My first intuition is that it would be an improvement over omni-present `if err != nil {}`, but it feels somewhat awkward and tacked on. Especially the mutable `err` return value.
Of course there also was a reason why try! was replaced with `?`: awkward nesting and chaining. Go would have the same problem.
Thanks to tuple returns being a bolted-on afterthought on the language, Go already features awkward and cumbersome nesting and chaining!
My main point is that this somewhat weird pattern is encouraged by the proposal since no other wrapping mechanism exists. And IMO wrapping is really essential for debuggable code.
Pretty underwhelming for what's supposed to be a modern language.
The key characteristic of Go's error handling is that you have to handle errors in the scope in which they occur, vs. exception handing which is designed around throwing errors up the stack until something finally handles it, often quite distant from the point of the error and lacking context.
"try" just re-spells that. It isn't a step towards exception handling; it's exactly as "exception-handle-y" as if err != nil { return err } already is, whatever value you may consider that to be. Part of the goal is to make correct handling where you actually do something with the error that much easier, instead of having to do something essentially unrefactorable for every error, through a combination of allowing error handling to be factorable in this new scheme, and some other changes to errors to add more structure by convention to create official ways of composing them together and examining these composed errors in sensible ways.
For example, consider a bug that causes a data structure invariant to be violated. The correct "handling" of the situation is to fix the bug and rerun the code, not add layers and layers of error "handling" code ahead of time.
So there's still plenty of time to stop the proposal.
Most functions in Go have a contract that the return values are disjoint, or mutually exclusive — they either return a valid value or an error:
s, err := getString()
if err != nil {
// It returned an error, but "s" is of no use
}
// s is valid
This pattern so ingrained that there's hardly a single Go doc comments on the planet that says "returns value or error". The same goes for the "v, ok := ..." pattern.But this is just a pattern and not universally true. A commonly misunderstood contract is that of the `Read` method of `io.Reader`, which says that when `io.EOF` is returned, the returned count must be honoured. This is an outlier, but because the convention of disjointness is so widely adopted, many developers make this assumption (it's trivial to find repos in the wild [1] that make this mistake), and so this is, in my opinion, bad API design.
(As an aside, it's also true that multi-value returns beyond two values almost always become cumbersome and impractical, especially if said values are _also_ mutually exclusive. Structs, having named fields, are almost always better than > 2 return values.)
This kind of careless wart is typical of Go, just like other surprising edge cases like nil channels (or indeed nil anything).
I would much rather see a serious stab made at supporting real sum types, or at least mutually exclusive return values. For example, I could easily see this as being a practical syntax:
func Get() Result | error {
...
}
This union syntax showed up in the Ceylon language, and it's a neat pattern for a conservative language that doesn't want to venture into full-blown GADTs.Such a syntax would be a much better match for a try() function, since there's no longer any doubt about the flow of data — there's never a result returned with an error, it's always either a result or an error:
result := try(Get())
or simply support existing mechanisms for checking: if err, ok := Get().(error); ok {
...
}
if result, ok := Get().(Result); ok {
...
}
switch t := Get().(type) {
case Result:
// ...
case error:
// ...
}
I'd love to see a `case` syntax that allows real local variable names: switch Get().(type) {
case result := Result:
log.Printf("got %d results", len(result.Items))
case err := error:
log.Fatal(err)
}
And of course, you could have more than two values: switch Get().(type) {
case ParentNode:
// ...
case ChildNode:
// ...
case error:
// ...
}
The Go compiler can be strict here and require that every branch be satisfied or that there's a default fallback, although some might prefer that to be a "go vet" check.A full-blown sum type syntax would be awesome, though I know it's been discussed before, and been shot down, partly for performance reasons. Personally, I think it's solveable. I'd love to be able to do things like:
type Expression Plus | Minus | Integer
type Plus struct { L, R Expression }
type Minus struct { L, R Expression }
type Integer struct { V int }
[1] https://github.com/search?q=%22read%28%22+%22if+err+io.EOF%2...https://doc.rust-lang.org/rust-by-example/custom_types/enum....
But Rust is an advanced language. In the company I work for, Rust would be a no-go simply because some developers would struggle with it too much.
Go hits a nice sweet spot. You don't need to worry too much about whether something is on the heap or stack, or what the overhead of copying a struct is. It's conducive to incremental "sculpting": You can write a broad, naive implementation where you even wing it a bit with types first, and then slowly fill in detail, refining types (to the extent Go lets you), locking down performance, and so on.
My feeling with Rust is that you start and end with just one level of granularity: You can't really defer the implementation of lifetimes and copying semantics and so on until later; you have to add clone() at the beginning, whereas Go is all copy by default (with the exception of interfaces).
But yes, Rust's enums are much nicer than what Go has.
The good news is if you hate it you don't have to use it, but since it'll be in the language (if they take it) you'll have to know how it works.
I don't think this is worse than things like "for:else" in Python.
The designers hope to give Go users “what’s needed to write good code” without having the learning curve of other languages.
I suspect this balance is hard to strike at times and I rather admire their efforts.
When an error occurs people should be doing what they already should be doing. That is to say, immediately log/wrap the error with context (file + line information) so that the error can be immediately found. Then if there are any callers of this failing function, they are the ones who should use try.
func A() error {
if err := do(); err != nil {
log(err)
return err
}
return nil
}
func B() error {
try(A())
return nil
}
To be honest though, I don't personally like this proposal.I guess that's the idea of Go, to restrict the language power by giving just the functionality the designers think the programmer should have, but to not allow anything too fancy.
However, if you put some thought to it, it really sounds silly when you know that this will only limit your ability to actually use the language and not really "simplify" anything, since it only adds to the general cognitive load of the language - in this case, one more exceptional case.
You are suggesting that they implement a metaprogramming system (and then build this solution on top of that) instead? On the grounds that it will reduce cognitive load overall?
Surely that is a drastically more difficult solution to the problem this is meant to address. I think it might be difficult to implement that in a way that maintains key properties of Go (like consistently fast compile times), and it might add a lot more work to tooling that needs to understand code like editors etc. And although that would allow each Go project to invent their own error handling mechanisms, and some projects might benefit from that, there's clear downsides to that as well.
BASIC and VBA are extreme examples but they support my opinion :).
Go has a ton of shortcomings. No good popular package management system with versioning, hacky JSON parsing, no generics. Rust is becoming a good counter example, they listen to the community and pump out features that everyone is excited about. Like async recently.
Google has a habit of ignoring the community. Angular is a great example. I've been following a feature request for close to 3 years that has over 100 comments asking for it. A simple thing too. Many people have opened PR's and begged for it in vein, even as recent as a week ago.
Not having to deal with inheritance is clear and readable enough. Generics wouldn't make the language less clear and readable. Furthermore, it's not an ALL or NOTHING case. Generics could be restricted to generic functions for instance, not types per say. Go already makes a lot of trade-offs, i don't see why this trade-off would be controversial.
But to me generics are the least of Go's problems. A lot could be done to make the language easier to use, like co-variant interfaces for instance, a tons of other stuff could be added in a relative "invisible" fashion that would not impact the language's syntax.
https://fosdem.org/2019/schedule/event/kubernetesclusterfuck...
f := try(os.Open(filename), "opening config file")
Place the context string just after the last, error parameter. That is, make try also also allow the pattern: try( a1, a2, ..., error, string ). Bonus points if the last arg could be a func(error) error, that way you can pass a local closure to wrap the error in a scoped context and also avoid pre-calculating an expensive error string even in the non-error case.It's just a language feature, you can make up any interface you want. We're already on the magic train, might as well ride it.
I think this is a rather large improvement to error handling. I need to read more about how it works with "go" and "defer" (it's all in there).
Try can only be used in functions that use error types as the last returned type. The compiler should be rejecting uses outside of that. So why is this any harder than thinking about "go" or "defer"?
fmt.Fprintf(os.Stdout, "%s: %d\n", try(getID()), try(getCount()))
a function may return in surprising places.Since we're talking about the application of "bind" you could think of the "invisible semicolon" in Go as the same kind of bind between "try" statements in Go, and get very similar behaviors - conceptually.
At least, that's how I think I've understood "try" to work.
(pseudocode... )
f := try(open(...))
num_bytes := try(write_some_bytes(f, ...))
I hope my function bailed out early at "f := try(open(...))" because the line "num_bytes..." literally makes no sense at all if f hasn't been even declared "f :=" vs "f =".
In the end, if I don't like it, I don't have to use it, but I still have to understand it if it's in the language and I'm reading other people's code.
I see it the other way around. I'm in favor of generics for Go, but I can't support this design and I think it will have a negative effect on library stability.
Rather than narrowing the scope of contracts to remain mostly orthogonal to existing features, they have it totally open-ended. They clearly didn't want to put too much restraint on what can be stipulated by a contract, and consequently it just feels like a solution looking for a problem (or like they didn't want to to make any hard decisions for which they might be critcized). With contracts as they are, they are incredibly powerful and stomp all over the type system and interfaces in terms of their practical utility. This is not orthogonal design, or really any sort of design, it's a blank page. They feel like a complete abdication of the designers' responsibility to make Go a simple language that tries to only pull in minimal features while reducing overlap. It's context.Values again but far worse. Please stop trying to make everyone happy, it's impossible (and I realize the irony here).
I liked generics when they were going to be super strict (and consequently super simple from the user's perspective), no upper or lower bounds on the type, just essentially a glorified gogenerate. This feels like you all are trying to answer to the critics rather than to the code.
When this is in common use, it will greatly improve the visibility of non boilerplate error handling.
- A built-in Go error check function, “try”.
- Allow embedding overlapping interfaces.
- Diagnose string(int) conversion in go vet.
- Adopt crypto principles.
Turn a profit by pumping crappy tech to the masses?
https://gist.github.com/kyleconroy/e48c83425349f2d3954d4e764...
I'm not a fan of the verbosity at present either, but seems like the check/handle syntax is less direct and the try()/defer func syntax is less flexible.
handle err {
w.Close()
os.Remove(dst) // (only if a check fails)
}
the error returned from w.Close() is not handled.On the other hand,
w := try(s.Create(dst))
try(io.Copy(w, r))
try(w.Close())
return nil
this code has the problem where if there were an error in the `Copy`, the file descriptor would be leaked.So, yes, one of the examples is wrong.
I understand that the current error handling is a bit too verbose but at least it makes the code readable.
I am not sure if this is really the best way to fix this issue TBH.
""" As we saw above there is no way in Go to have immutable data structures. This means that once we send a pointer on a channel, it's game over: we share mutable data between concurrent processes. Of course a channel of structures (and not pointers) copies the values sent on the channel, but as we saw above, this doesn't deep-copy references, including slices and maps, which are intrinsically mutable. Same goes with struct fields of an interface type: they are pointers, and any mutation method defined by the interface is an open door to race conditions.
So although channels apparently make concurrent programming easy, they don't prevent race conditions on shared data. And the intrinsic mutability of slices and maps makes them even more likely to happen. """
Is this still a concern, and if it is, would it be addressed in Go 2?
How you can write simple, reliable, and efficient user code (https://golang.org) if using your favored concurrency model results in race conditions?
You can't. And the language is not expressive enough to be able to write generic immutable data structures as you have in Scala/Java/Kotlin/etc.
I think with 1 sender and 1 receiver the common solution in Rust is the same, to copy (or maybe move) the values sent... the type system provides some safety guarantees but I doubt it would be much different for performance. You wouldn't be able to send an immutable reference over a channel in Rust, since the compiler wouldn't know where the reference's lifetime ends. You could resort to refcounting, but you would probably only put in the effort if the data structure was large enough that copying was prohibitively expensive.
Go also provides mutexes that are more suited for that.
Sure, passing a pointer through a channel does not in itself provide any protection to the data it references but such protection is not always required. There's a separation of concerns that allows more flexibility.
Safety should be the default, with a way to opt out for people who have thought really hard about the consequences. If I have to opt into the safe version, I need tooling to complain about everywhere I didn't do so.
It's not rocket science.
Goroutines are supposed to be lightweight so it makes sense to allow lightweight communication.
Yes, as long as you keep sharing the references. So just don't reference that stuff you sent across a channel. Usually there is little reason to use pointers in Go anyway [1] except when building methods to mutate the associated type (think: struct).
That said, it's fairly easy to build cascaded structures that are automatically deep-copied during assignment by not using pointers. So that's a pretty safe way to go, moreover one should keep in mind that Go doesn't try to be functional in any way, so immutable data is not such a thing there.
[1] https://medium.com/@vCabbage/go-are-pointers-a-performance-o...
f := try os.Open(filename)Big if true. It's one main complication keeping me from adopting Go for more things.
When it comes to error context it would be nice to facilitate structured logging, rather than arbitrarily formatted strings.
type T generic {
+(T) (T)
==(T) (bool)
}
Donno where to suggest this.edit: clarify.