Next steps toward Go 2
blog.golang.org
blog.golang.org
- 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.
Some of the core advantages of Go over Java are less pronounced with C# since C# has async/await, value types, easier C interop, unsafe, etc. The tooling for C# is great too.
C# also has bindings through Xamarin/Mono for iOS/Android/Windows/Mac development that the Go ecosystem doesn't really have an equivalent for. And of course there's Unity for 3D stuff.
There's some minor things like Go being a little less verbose or having a little easier learning curve, but I didn't really find those to be significant problems when using C#.
The main reason I'm using Go right now is mostly the GC properties. It's easier to avoid allocating memory but also the pause times are much lower than most other GC languages including C# [1]. For anything where latency is important Go is an interesting choice these days since it's hard to go any lower without adopting some form non-GC memory management.
https://cdn-images-1.medium.com/max/1600/1*_Nom6vNYqIAqozgK0...
Then check their compile times, language features vs Go.
Or even better, get Turbo Pascal 7 for MS-DOS and run it on DosBox.
It is only impressive for developers that never used such languages.
Additionally it has been available in Mono and other runtimes as well.
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.
Also, even if go were better than all other languages, it still might not be perfect.
Let’s say there are 10 ‘objectively good’ programming language features.
If most languages have 7, but go has 8, you still can complain about wanting the two other ones.
Considering all the successful software written in PHP...? Or Javascript...? Java...? Your argument absolutely has nothing to do with my point.
"Langues do not need function calls, successful software has been written in assembly" is a pretty weak argument.
https://medium.com/@arschles/go-experience-report-generics-i...
How much of that software doesn't use Go's internal generics?
It is such a lousy metric "if it is used it is good".
Well PHP and JavaScript are also used, a lot, even more than Go, most likely bringing home much more revenue as well.
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.
https://github.com/golang/go/blob/3813edf26edb78620632dc9c7d...
My guess is they don’t have anything usable by the end user any way, otherwise they wouldn’t spend so much time thinking about a design for go 2. It probably means whatever is in the compiler isn’t that elegant, nor reusable.
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.
Dep was made by one of the authors of Glide, which coincidentally suffered from many of the exact same bugs, maybe because it reused some of the same code. Our entire team constantly had "dep ensure" failing in unpredictable ways (locally or on the CI server), usually caused by the solver not understanding something. These failures were completely incomprehensible and not fixable by the user. Dep's solver was also very slow.
From what I could tell, it was a combination of shoddy engineering and trying to do too much; if I remember correctly, Dep and Glide both tried to automatically detect and convert dependencies that used competing tools like Godep, which didn't work very well. For a long time, Dep didn't work at all with the Kubernetes client library, for example.
We've had almost zero problems with Go modules. I've encountered some minor bugs, but unlike Dep, nothing worth tearing my hair out.
The drama around Dep vs. Russ Cox shouldn't have happened, of course.
I have found the package management story around go so confusing its really stopped me from trying to use the language.
For context, I'm used to how composer/npm install the modules into a folder locally. I just can't seem to figure the go way of doing modules where I don't get completely confused.
This article looks like a good intro: https://roberto.selbach.ca/intro-to-go-modules/
The equivalent of "npm install" is "go get" (optionally "-u"). You can also edit go.mod manually. Like NPM, this must be done within an application's root.
A point of confusion might be the difference between a module and a package. A package is just a folder that declares "package foo" at the top in all its Go files. A module is the closest analogue to an NPM package. Similar to NPM, a single Git repo can contain many nested modules. Unlike NPM, modules can be imported with Git -- no need to publish to a special registry.
When a Go file imports a package, the referenced package might live in a module outside your own. It knows it's outside your module because go.mod defines the full root path (e.g. github.com/foo/bar/baz) of your module.
You might experience some confusion when you look at how the new module system interacts with the old GOPATH way. Go current supports both modes.
Likewise, the community doesn't have any say in how try works, and that ticket asking for feedback is window dressing.
You can tell that this is window dressing by looking at the timestamps on when that ticket was opened, comparing it to when this blog post was released, and then considering how the hundreds of comments on that ticket were completely ignored.
Dep was pretty good, and there was absolutely the possibility of just making that official (and maybe tidying away a few of the points raised during the module discussion). But no, that wasn't good enough.
Dave Cheney's errors package (pkg/errors) is a great contribution to Go error handling, used by a lot of gophers. Adopting that would have been simple, backward-compatible, and given us better error handling. But no, that wasn't good enough.
I'm so used to "if err != nil" that it's punctuation for me. Having some code use "try" because it doesn't need to be wrapped, and other code use "if err != nil" is going to break that. I'll have to actually read the error handler now, in case it does something unexpected.
Or not use "try" and stick with errors.Wrap. That seems way more sensible to me.
it's not democracy, but they'd be stupid to just ignore all that expertise.
Sure
Semantic import version and the rush of shit to the head in their attempts to break vendoring on the other hand.
I think I can live with it.
This is the C# 9.0-ification of a language. Let's add more constructs because we're compiler developers and that's what we do.
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...)
"don't use it" is definitely an option, but it's nowhere near "it doesn't exist". It's opting into a constant struggle against the tide.
At the same time we are surviving the type aliases quite fine (who has ever seen them used? Not me...)
You night not have used them directly but you might have benefited indirectly from type aliases. For example, when the "context" package has been moved to the stdlib aliases allowed existing libraries that still used the old "x" context package to be used together with code that used the new package.
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.
These tools are so common and so normal that while they aren't part of the compiler, they're part of the "social" toolchain.
So, it's odd that the author doesn't use a linter when the general tendency is to use a linter, a licensing checker (glice), a security scanner (gosec), a formatter (fmt), a static analysis tool (go vet), etc in your CI/CD pipeline.
It's so odd that it begs the question - does this author avoid common tooling? And by extension, do I care what they think about how Go should be written if they aren't using the standard tools?
Even if the try proposal were to result in eventual go vet errors, then surely go fix would be able to rewrite on your behalf, so this would be a non-issue, just as go fmt is a non-issue. But I don't think this will happen any time soon.
> everything that is `return nil, err` will need a special comment to silence recommendations
I don't use linters that can be ignored with special comments. I don't recommend them. This is a problem in other languages/ecosystems, but in my experience it is not a problem in Go, where it's considered an anti-pattern. This feels like FUD to me.
> nagging social pressure to reduce linter warnings will result in skipped error handling.
Yes and no? Social pressure to reduce linter warnings is a good thing, why use a linter if you are going to ignore its output. This problem only exists if you have linter warnings.
> a licensing checker (glice)
I've never encountered this. I don't think a linter that hits the Github API is a good idea.
> a security scanner (gosec)
This looks like a pretty opinionated linter. Some example rules:
> G103: Audit the use of unsafe block
> G104: Audit errors not checked
> G201: SQL query construction using format string
> G105: Audit the use of math/big.Int.Exp
> G501: Import blacklist: crypto/md5
Are these actionable? Probably not. There are perfectly valid reasons to do all of these things. Maybe this is useful to paint a picture of a code base you're evaluating, or to flag new changes as suspect, but I don't know what purpose this would serve in CI.
Don't use linters which just create noise and non-actionable output. They're not valuable, they're a waste of energy. Make them manual, or maybe run them against new changes only with the expectation that they're informative but often ignored.
These are all personal problems. Most Go users don't have these, I suggest you choose to not have them also.
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.
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
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.
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.
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.
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.
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.
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. fmt.Fprintf(os.Stdout, "%s: %d\n", getID(), getCount())
Could have hidden panics in it and you would never know.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.
Same thing applies to the STM "subset" of Haskell -- conformance to which is statically verified by the type checker[1].
[1] There's no particular magic going on wrt. checking -- STM is a monad. It just happens to have "magic" runtime support.
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.