[0]: https://github.com/golang/go/issues/29934#issuecomment-48968...
[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.
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.
Also, in a function with a couple of different error types, do you end up checking the error type manually and reacting accordingly, all in one final defer? That seems error prone. And it doesn't work at all if multiple statements can produce the same error - you won't know which statement caused it.
And, last but not least, this would loose proper backtrace information: the backtraces all point to the defer line rather than separate lines for each error.
I don’t know what error types has to do with it. If you need to annotate differently for every exit point, sure, a defer doesn’t work, but neither would any other proposals I’ve seen. In those cases, do the more verbose thing because the verbosity is apparently warranted. In my experience, it is rarely warranted, and a stack trace with annotation about the package/general operation is sufficient.
The stack traces contained still include what line the return happened on when queried from inside the defer. They retain the information about which return executed. My, or any, helper could, if desired, explicitly skip the defer stack frame, and it would be indistinguishable from capturing at the return itself.
It can't happen. The compiler forbids it: https://play.golang.org/p/65bFHrgGblb
> Also, in a function with a couple of different error types, do you end up checking the error type manually and reacting accordingly, all in one final defer?
If a function needs to check the error returned by another function and act accordingly, then don't use try() and use a if statement.
If we just need to decorate the errors with proper context before returning them to the caller, then we use try everywhere and a single defer statement for the decoration. We can use a single defer statement because we expect that the error context is the same in the whole function. See this comment by Russ Cox: https://github.com/golang/go/issues/32437#issuecomment-50329...
> this would loose proper backtrace information: the backtraces all point to the defer line rather than separate lines for each error
No. In the deferred function, you can get the line of the actual return: https://play.golang.org/p/7MVZupCLh5F
Thanks to tuple returns being a bolted-on afterthought on the language, Go already features awkward and cumbersome nesting and chaining!
Pretty underwhelming for what's supposed to be a modern language.
Go is only inevitable for those that need to deal with Docker and Kubernetes, the NoSQL hype successors.
Personally, I find Rust as more approachable and easier to wrap my head around opposed to Go. Though some of the syntax changes I don't like as much. Waiting on async/await to land in a couple months though.
I believe that after I fully integrate the Zen of Rust, that I will be writing multi-threaded programs with fewer bugs than I would in my alternative languages (C, C++, Go, Python, Lua).
The annoying things in Go that have accumulated in my mind over the last few years are all dealt with in a superior fashion in Rust today.
I'll still be using Go for some stuff at work, but I won't be starting personal projects in it, like I might have in the past.
Although to be fair to Go, I don't think ALGOL 68 had a (slightly broken) implementation of CSP and HTTP/2.0 support in the standard library.
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.
def handle(request):
try:
return Response(200, process(request))
except UserError as ex:
return Response(400, ex.message)
except InternalError as ex:
return Response(500)
The principle stays the same, there is not much to "handle" and no option to recover without external help, either by providing a well-formed request for 400 errors or by providing well-behaving code for 500 errors.There are legitimate criticisms to be made of how Go's error handling works, but I think the language already handles the case you're talking about.
"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.
A. Create an error object, enter "error mode".
B. Annotate an error object with contextual information at each call point.
C. Return the error object up the call stack.
D. Translate from "error mode" into "value mode", producing the annotated error object as a value.
For languages with exceptions, B is automatic, but limited to stack traces, C is automatic. A and D are obtained via special language constructs, for example "raise ... / try: ... except E as ex: ...".
For Go [please excuse my almost total ignorance], B is manual, but arbitrarily expressive, C is manual, but terse via "try(...)", whereas A and D are done using a combination of standard language constructs and style conventions.
Assuming the above is correct, perhaps there is some reasonable design that automates B for most common use-cases. In particular, logging the invocation arguments at D makes it trivial to re-run the offending code in a debugger, with full stack trace and invocation arguments. Wrapping most function calls with "try(...)" is annoying, but manageable, whereas thinking what information should be carried by the error object on a case by case basis is a waste of brain cycles.
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.