by AtroxDev · 7y ago · 0 comments
[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.
I suspect it's only "somewhat weird" due to lack of familiarity, and that adding an additional mechanism to wrap errors when one already exists is not in the spirit of a language built from small orthogonal components.
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.
"Handling" an error includes further annotating it with information about why the code in question couldn't fix it, and this is probably the most common case. (I hedge only because we humans are actually really bad at judging such things, with our availability heuristic bias and other biases. I'm fairly confident this would indeed be the #1 case, but I've been wrong about this sort of thing in the past when I actually went to check.) We don't mean "fix" the error, just... "handle". Ideally you end up with a composite error object (as I said, in conjunction with a few other library-level things that are likely to get pulled up to official support and culture) that contains much more information about the error, and that if you do end up flinging it up to higher level code, you're leaving it with more options for understanding the resulting problems and dealing with them.
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.