241 points · by dimonomid · 8y ago · 185 comments
As to the minimalism in Go, I wish it came with a few more default data containers.
Sorting a map by using a slice gets old after awhile. Why can't I pick a sorted tree based map (like std::map or std:set in C++) or an un-ordered hash based map like std::unordered_set, etc.? Why do the containers have to be so minimal too?
This just leads to people rolling their own and many times, that leads to poor performance and other issues which ultimately reflect poorly on the lanaguage. I've seen more string implementations in C than I can count. Most of them were bad. I hope Go doesn't end-up being like that.
- https://github.com/timtadh/data-structures ## I wrote this one.
- https://github.com/Workiva/go-datastructures ## this one is also popular.
- https://github.com/golang/go/wiki/Projects#data-structures ## big list here.
I've written them over and over, myself. They're all bad, because the problems are nigh insurmountable:
1. C string literals don't know or care about your string package.
2. Once you step outside of the string package, you're incompatible with everything else.
3. C determinedly and resolutely devolves arrays into pointers. https://digitalmars.com/articles/b44.html
Nah, Go was careful to make that impossible. (You know exactly what I'm talking about, I'm not going to come out and say it. What one, specific thing makes rolling your own container in Go literally impossible?)
(I'm actually guessing... This isn't my domain)
(Unless of course you do code generation...but then you're not writing Go, you're writing a program that writes in Go.)
Containers are the level 0 of generic data structures: not only is an "array" significantly less useful than an "array of T" it also leads to loss of safety (you may intend your array to be an array of int, but codegen aside there's nothing precluding a user from shoving a string in there) inefficiencies (since the type of values must be erased you need an indirection, usually a pointer) and usercode-complexity (the user needs to downcast all values to the data type they hope they are).
1) No constructors. When I create a struct, without a constructor, I can't be 100% if certain fields are populated or not. With a constructor, I could force this. With a large number of people working on a code base, you can't assume anything, unfortunately, but without a constructor to force exact data in a struct, it makes it more tedious to be sure.
2) Error handling is ugly and tedious. Not being able to get the type of an error makes it a lot more inconvenient. At least in our codebase, errors are almost string parsing, it's ridiculous.
3) Nil map vs empty map is a very strange thing to keep in the code. Why even allow this distinction?
4) Named return parameters are really stupid. This is another thing that doesn't fit the philosophy of what I understand Go to be. It forces a bunch of verbose opinionated rules on us, but then allows named return parameters which causes confusion.
5) It's very hard to tell the difference between package names vs structs. Luckily Gogland allows you to change the color for package names so this helps me out tremendously, but there should be a better way to differentiate without relying on your IDE.
Overall it's okay but nowhere near perfect and has some really weird deficiencies. The company I work for uses Go with dependency injection which I hate and I think is very ugly but a paycheck is a paycheck.
2) You can always encapsulate errors. Your code will still have a type assertion or switch, but you don't need to use string parsing (although I have seen string parsing used in libraries such as mgo - the MongoDB client library).
3) Because maps are references, just like slices. You can still call len() on a nil map and therefore treat it as an empty map? If you mean the assignment to nil maps: https://groups.google.com/forum/#!topic/golang-nuts/RkYIF8Sq...
4) This is subjective I think, but I disagree. I like just being able to type "return" instead of for instance typing in 6 different places "return something, err".
5) Do you mean un-exported structs (and therefore lowercase)? I haven't come across this, but I can see where it could be an issue. I usually just use VSCode and mouse over to quickly see a name's definition.
I agree with you that it's not perfect, but as I saw someone else say on the internet, it's the least bad language (in my opinion). And I don't envy you for working with dependency injection in Go :)
You can create a function which makes (and populates) the struct.
For example, https://play.golang.com/p/rvSvEZNkXe
>Error handling is ugly and tedious. Not being able to get the type of an error makes it a lot more inconvenient.
See https://stackoverflow.com/a/7006853/5849285 to switch on type (error is a interface with a Error func[1]), so you can define different error types [2], or use `int` to define error type.
[1]: https://blog.golang.org/error-handling-and-go [2]: For example, os.Open returns a * PathError
They exist because go really has exceptions. The only way to "catch" and modify variables in the "catch" before they are returned is to use named return values. You can't return anything from a panic/defer/recover directly. Error as value are just a convention.
You can make arbitrary types implement the error interface. Your custom error type can carry all the information you need. If err != nil you make a type assertion and access the error’s information. See [1].
Is there something similar to opaque types in c? Like a "constructor" function that returns an interface and then methods that operate on the interface instead of the struct itself?
What I don't get about go is why certain trade offs were made, some work well for a systems language, like error codes, but then there are different trade offs that don't, like the GC. Similarly the GC makes sense for a high level apps language, but features like lacking generics don't.
Error handling in go feels like going back to 1960s programming.
Garbage collection is already implemented with high performance in Java and other platforms, what's new? You can use GC with different strategies in C++ as well, if you like, the libs are there. There are many libs to get dynamically managed memory in C. But the author wants to program for embedded devices and my choice there would be to avoid dynamically managed memory for the most part.
Coroutines and tons of different concurrency and multiprogramming and parallelism paradigms and strategies are already available for most mainstream languages.
Syntax in Go looks like a poorly done copy of Algol-68 (1968, and -surprisingly- a more powerful language.) Why?
At least if they would have went with s-expression syntax, they would have enabled metaprogramming and this would have solved some of the problems with missing features.
As for use in embeddable devices, the author discards D and other languages for lack of portability to other platforms; but AFAIK embedded devices programming goes to very low level details and thus I can't think how a code that is tied to the specific hardware would be portable, no matter what the language is.
I thought Google had smarter language designers. At least Mozilla did a decent effort with Rust. Perhaps Google do have smarter engineers and they actually use Julia, Lisp, and Smalltalk for Google's internal projects...
A simple language that can be used for both 'scripting' projects and larger applications, natively, statically compiled, with a modern standard library aimed at what a lot of "ops" development is currently in need of. Hence the explosion of tools written in Go targeting that field. Maybe it's not suitable for your applications, but there is clearly a market for this.
> but AFAIK embedded devices programming goes to very low level details and thus I can't think how a code that is tied to the specific hardware would be portable, no matter what the language is.
That depends on the type of embedded stuff. I wrote a ton of embedded code targeting various embedded OS's on POS systems running m86k, MIPS, ARM and other stuff. I was responsible for designing and writing a generic hardware abstraction layer. It took considerable resources, but once streamlined, porting to another platform took about 3 months (if the hw and compiler/toolkit vendor were helpful, otherwise it could take years). It gave us the massive advantage of being able to develop/debug/showcase the application logic on a PC or on alternative hardware, and then finally target the real hardware when the HAL was finished and work out some kinks there, taking another month or so. So yes it's absolutely possible to write portable embedded code.
> I thought Google had smarter language designers. At least Mozilla did a decent effort with Rust.
Given the adoption rate of Go in the ops field, which incidentally is what Google needs a lot, I'd say they at least got something right.
...but it's very portable. It has llvm and gcc backends, supporting whatever platforms those support (all that you're likely to ever use), and it's possible to compile without runtime/gc, for a small enough footprint to run on embedded.
Really? Knowing that it's the likes of Rob Pike or Ken Thompson?
If you had told me ten years ago that these guys are going to make a language for Google, I'd have accurately predicted that it will be exactly the same sort of insipid blub that it is.
They are not going to see very far outside of the C + UNIX box, and much of whatever they do see, they will have an allergic reaction against.
They do, but you may be misunderstanding the purpose of Go for Google. It's to take recent untrusted grads and have them be quickly "productive" generating reviewable code.
It's not an accident that Go's feels a lot like a somewhat improved and simplected Java (1), very much tuned towards network services.
Interesting. Do you think having that syntax would help with developing generics for Go (a thing that I've read a lot of devs feel want to be there in it)?
Some of us remember, however, why we left C behind (it does not work beyond a certain degree of complexity). Why would I want to do Web programming in C? We spent years creating better tools for this.
Yeah, but it's pretty good for small simple projects, like the Linux kernel.
It's so large its creator invented a sophisticated VCS to manage it.
There aren't many projects like the Linux kernel.
A large number of the common kernel bugs, such as refcounting errors, buffer overruns, messy goto logic (resulting in use-after-frees sometimes) are because the kernel has had to build up poor abstractions due to their language not supporting better abstractions.
This is my list of things that Go does better than Java; I don't want to give the impression that Go is perfect--I have lots of criticisms for it (no generics, hacky workarounds for sum types, error handling is often too simple out of the box, no decent REPL, etc), but it lets me be more productive than any language I've used to date.
Simplicity of deployment is nice, but the main reason I don't use Java is because it's just painful to write. I had to write some Java just the other day to duplicate a bug a customer bug and it was tortuous.
I feel like a lot of the things I find tedious about Go should be much easier to generate somehow so I can get on with what I was trying to do. sqlboiler is an interesting version of something that Go by-it-self can't provide without code generation if you require not using reflection.
Otherwise, I like the language a lot. I mainly love it's simplicity to deploy, good cli, and low memory foot print. I also like that it's very easy to read, that the community is focused on "reading code", and that there are many good libraries out there now in addition to the standard library.
Started looking at Scala recently, and I'll probably play around with it, but it just seems Go is so much nicer to use for the kinds of projects I'm trying to develop.
Right now, we have the magical //go:generate comment, but since it requires manual invocation of "go generate", artifacts can and do get out of sync with the Go code.
It would much nicer if Go code could contain code that caused generation to happen when the code was compiled. Adding the ability to execute Go at compile time would be one possible solution, similar to Rust's custom derive [1] support. As a use case, Rust has libraries that make extensive use of this system, such as serde [2], which can automatically generate efficient, type-safe serialization/deserialization code for structs (e.g. to/from JSON).
[1] https://doc.rust-lang.org/book/first-edition/procedural-macr...
It's pretty easy to enforce that as a build constraint in your CI system; we do that with our Go projects. If the output of `go generate` isn't checked into git, the build fails. (Same if the code hasn't been formatted with gofmt).
On the other hand, lack of proper vendoring, version pinning and getting random versions of libraries off GitHub makes a lot of people anxious about long-term reproducibility.
Like a peer of mine once said, “maven is forever. They don’t call things ‘artifacts’ for nothing, I can even do archeology in my dependencies”.
I created a small bash script (called giclo) which automatically places checkouts of git repo's in the correct ~/code/src/HOST/USER/REPO directory, super convenient and very well organized.
I don't get this. In practice, most functions end up having an error result by convention, so the answer to "can the exception be thrown here" is always "maybe", which is the same as the answer would be to any function call in a language with exceptions...
I do appreciate the difficulty in balancing simplicity and verbosity, but there are a handful of cases in Go where I wish they added some complexity to make the code significantly more terse.
https://gist.github.com/lattner/31ed37682ef1576b16bca1432ea9...
You just don't have a big community building server tools and libraries around it yet.
This appears to be a decent starting point to further enlightenment: https://davidnix.io/post/error-handling-in-go/
Only the most trivial functions don't have the possibility of error. And if a function doesn't have an error condition today doesn't mean it won't be changed to have one tomorrow.
Java has ruined too many programmers on exceptions by making them checked and making you do a lot of unnecessary try/catch dancing. A program should only have a few key try/catch blocks in the places where recovery is possible and it should be only concerned with what it can recover from. This obsession with every error that any method can throw/return is entirely the wrong way to deal with exceptional conditions. Therefore, error handling in Go is as backwards as it comes.
Using `Result` types as your only mode of error handling makes that API contract explicit.
I get that goroutines are great, but that really seems to be all Go has going for it. The GC sucks, error handling feels like something from a bad language designed in the 70s, missing generics, math library is awful, Rob Pike being super opinionated, etc.
It's more like every 5 lines. I love it as every error is handled correctly and in scope. No error is left behind. Most languages I've used devolve into the GLOBAL MASTER DEFAULT HANDLE ALL ERRORS which is just gross.
For example, consider:
foo, err := getFoo()
Now your scope has an "err" and you open yourself to logic errors such as: foo, err := getFoo()
... do stuff ...
if errr := makeBug(); errr != nil {
return err
}
Spot the (heh) error? It's caused by ":=" allowing variables to be reassigned.You can avoid this dangerous pollution, but it's super ugly:
var foo *Foo
if f, err := getFoo(); err == nil {
foo = f
} else {
return err
}
(You have to have the return in the second branch, otherwise "go vet" will complain. Sigh.)I have lots of these, and they're not helped by the fact that Go has no type-level mechanism to guard against the misuse of multiple-return values. That is, in the above, either "foo" or "err" are usually set, and if "err" is set, it means "foo" isn't. But the type system doesn't prevent you from accidentally ignoring "err" and using "foo", or vice versus. This gets even worse if the func returns a (non-pointer) struct as its value.
The fact that Go allows shadowing (exacerbated by the convention of using "err" as every single error variable) and promotes the reuse of variables (e.g. the above ":=", or declaring "err" outside a loop) also means it's super easy to assign the wrong thing.
All of the above are my single biggest source of bugs during development. That, and how accidentally using nil/zero values, including the damnable nil map/slice cases.
"go vet" (whose shadowing check is disabled by default (!)) and the various linters only go some ways towards helping here. The errcheck linter (which you can enable through gometalinter) is absolutely essential.
Most functions return an error so err is already defined:
func doIt(a, b) (result string, err error) { ... }
Then you are free to reuse err as needed. func doIt(a, b int) (result string, err error) {
var x, y string
x, err = doA(a)
if err != nil {
return
}
y, err = doB(b)
if err != nil {
return
}
result = x + y
return
} var foo *Foo
if foo, err := getFoo(); err == nil {
return nil, err
}
// foo is usable nowI wonder what is the correlation between volume of complaining about minutia such as this compared to real life ability and level of accomplishment.
Not in scope. Because you are forced to deal with the error right here right now, sometimes it's in scope and sometimes, you're simply not able to do anything with the error so you effectively mishandle it.
Exceptions allow you to handle the error where it actually makes the most sense.
Anyway, Go-style error handling's lack of any of these issues is what makes it attractive to me: it's simple, straightforward and get's the job done. Granted, with a bit more typing and the occasional bug that could have been avoided by not having to type the (almost) same three lines once again, but not having to jump through any of the hoops I keep encountering in more sophisticated languages is so, so worth it to me. I feel like Go stays out of my way, lets me focus more on actually getting things done than on dealing with the language's intricacies.
Javascript messed it up a little bit with promises, because it's so easy to swallow errors. IMO, they should have made it so that unhandled promise rejections throw by default at the next turn of the event loop, with a method that could be called to opt out individual promises.
I don't think so. You can choose to ignore the error (I know it's bad practice), but it's allowed. And sometimes you don't know what to do with the error
I have said so in the intro textbook I wrote.
Go allows you to do certain things but it's not a fallacy because it's something that's allowed but not necessarily tolerated by what most consider "good Go coding standards"
For example: "if err" being compiled directly to "if err != nil" would be a quick win.
Second more complex idea: add a new keyword like "res := throw MyFunction()", being allowed if "MyFunction()" returns an "error" as its last argument and the calling function returns an "error" as its last argument, simply return the zero value or named return value of any other return values + the error if there is one, otherwise continue.
Point being, the core of Go is really good. When I come across a command line tool written in Go, my first thought is "fuck yeah, this is going to be so easy to install", versus something like Python which is a bitch unless the developers have taken the time to brew it or something. Countless planet-scale infrastructure tools have been written in it; Kubernetes and Docker to start. I can name a dozen startups, both large and pre-seed, which use it with resounding success.
Yes, it has warts. Every language has warts. Go is just "different" because it tries to be simple. Nearly no other language in the world has "simplicity" as one of its core values, and a lot of people don't fully respect what that means.
The real problem with go's errors is complex and significant.
There's no Either/Result type so the multiple return doesn't actually tell you that you get a zero value when there's an error (and in fact there are functions in the stdlib that do this).
There's no good way to check whether an error is a given thing because error chaining isn't built in and errors rarely are typed as sum-type-enums as they are in rust or other decent functional languages. For example, `os.IsNotExist(err)` will not work for a caller if I did `return fmt.Errorf("error opening file: %v", err)` in a function.
The stdlib encourage a dozen really bad methods of doing error handling; there's `io.EOF` (which is a mutable variable btw). There's PathError. There's os.IsNotExist. There's random panics in some functions. There's nil returns with no further info.
The stdlib has multiple examples of 3 or 4 different error handling styles, and they're all horrific because they don't chain and don't allow for exhaustive matching.
Go may be good compared to C or other languages that were designed way back when. In modern times, go is a massive step backwards with its incredibly underwhelming type system, absolutely asinine community, lack of good abstractions, and so on.
With all the things that you mention Go does not offer helps it keep simple. It has already proven much useful for many of of my projects where a 'better' language would fail for variety of reasons.
There is a huge difference.
The Java code you are reading is caused by bad programmers who are not using exception handling correctly. Proper exception use means sometimes catching and sometimes ignoring the exception and declaring it in your `throws` clause.
In Go, testing against `nil` every twenty lines is not only common, it's the ONLY way to write robust code. You simply don't have a choice.
I think same is going to be true for Go. I have written few projects in Go and they have produced much more value than time taken to write them.
At the end of day companies I worked for prefer mediocre code that is written and used vs excellent code in brilliant programing language that was never completed.
I personally like exceptions, as they enable focusing into what's supposed to happen instead of what all could go wrong. And the abstraction power that comes with this approach.
But I wouldn't rush to say I'm right and the meticulous party is wrong. There are many instruments in the orchestra. In the end all that matters is the skill of the player.
I don't like exceptions. Go's error handling is still ridiculous.
It doesn't have sum-types, it has the incredibly stupid interface/struct nil punning so you must return an interface and type-assert down, it doesn't have a tuple object being returned but actually multiple return which is a semi-broken thing, it doesn't have an either/result type or an optional type to express mutual-exclusivity / optionality....
Yeah, the whole thing is disgustingly bad. That doesn't mean I prefer exceptions.
I do prefer meticulous "errors as value" error handling. Go's implementation is the worst implementation of that because the type system doesn't support various features that make handling error values better.
The very best error handling I know of is in CLOS. Instead of exceptions, they have "conditions". A condition is signaled like an exception but with a big difference described below. The thing about errors is, the code that detects the error can never know how to deal with that error. If it did, then it wouldn't be an error it would be a case within that function. However, that code may know ways the error could be dealt with, it's just not in a position to choose. So what conditions do is, you can define a condition and so called "restarts" along with that condition. What the restart does is say "here is a way I could handle this error" and code higher up the stack has the option to (1) use the restart, (2) define additional restarts on that condition or let the condition propogate upwards. The condition signalling does not necassarily unwind the stack: if you choose a restart, the code continues in the stack that restart was defined.
So this means every part in the stack that knows how a condition could be recovered from can provide the option but it is left to code higher in the stack to chose the actual strategy. This is superior to the exception strategy of unwinding the stack until you find a handler because sometimes you really want the code to continue execution where it is.
But, of course, such a system is really expensive to implement. If you can't have that my preference is the Haskell style of using a sum type where errors can happen but writing as much of your code as possible with any error conditions prohibited by the type system.
Nobody used them, so we removed them.
I develop in Common Lisp and conditions&restarts are so much superior to the other error handling paradigms i've seen, that it's not fun being left without them.
Compared to Hotspot, it doesn't STW; it makes a different throughput/latency tradeoff that is more suited for its application domain; and it's actually needed a lot less often because the compiler can put many objects on the stack.
A generational collector is currently under development (but won't be in 1.10).
Stop the world typically happens during compaction phases. Golang "solves" this by just not doing any compaction. That's certainly a big tradeoff.
> it makes a different throughput/latency tradeoff that is more suited for its application domain
I don't really agree. While low latency is nice for consistency, low throughput means you may have to buy more servers to handle your load. That isn't always a win.
> and it's actually needed a lot less often because the compiler can put many objects on the stack
HotSpot can, and does, do this too!
> A generational collector is currently under development (but won't be in 1.10).
Does it? Do you have a link?
I haven't found any information about this.
> Does it? Do you have a link?
https://docs.google.com/document/d/1gCsFxXamW8RRvOe5hECz98Ft...
This is the original proposal, although I believe it has evolved significantly during development (in testing some of the proposed ideas didn't pan out as expected).
Not IBM or Azul, though, their JVMs already have kickass realtime collectors.
Go GC gets to make the claim that it doesn't "stop the world" because it doesn't do heap compaction. Which will become a major problem when dealing with large in-memory data structures or certain usage patterns.
And the fact that they still don't have a generational collector is concerning.
The bottom line is that the scavenger will allow the OS to claim free memory only at least 5 minutes after it was GC'ed. For us the solution was to "force" releasing the free memory to the OS [1], and even since then things have been much smoother in the context of our particular app.
On this topic, there's an open issue [2] to look at making the scavenger more prompt and aggressive.
[1] https://medium.com/samsara-engineering/running-go-on-low-mem... [2] https://github.com/golang/go/issues/16930
But I don't. For simple parsing or number crunching, Go is just right.[1]
I find the fast prototyping, the wonderful IDE environment (VSCode, vim), and the community to be _so good_ that I don't need anything else.
There was a time I thought of learning Python[2] or Rust, but found both lacking.
[1]. Sure, I wish I was smart enough to get a job working on Quantum, working as a kernel dev, or in fintech where every nanosecond counts. But I'm not. The Rust community is great, there's a lot of help out there, and it seems like an amazing and cool language.
[2]. I tried it out a bit. My main issue is that it doesn't (didn't) have nearly as good of an IDE community (PyCharm is practically the only good IDE for Python, and in the bit of time I spent with it, I found it much less powerful than their Java IDE) revolving around it.
At my job, for example, I'm slowly introducing bits of Rust here and there to do some data engineering. I wouldn't use it for high-performance numerical computations, but ergonomically it's almost as easy as Python (for me) and the safety, type, and other guarantees it provides make for a more robust pipeline.
All the fun stuff.
Edit: posting this because I'm in the same situation. I like Rust/Nim/Elixir but Go has a great productive ecosystem even though the language is quite "barebones".
When it comes to my default set of tools, I gravitate towards dynamic, expressive languages that provide greater leverage rather than ones with fast startup times, c-like speed, native binaries, etc.
That said, when you need those things, I agree with this guy--golang has been a far better experience for me than any other language of its ilk. I'm not claiming it has magic powers like rust or a sentient type system like haskell, but I spent hours learning go fundamentals, and days figuring out how to get real work done with it. I can't say that for many other languages with go's compile and runtime capabilities.
This was the pre-existing language: https://en.wikipedia.org/wiki/Go!_(programming_language)
Google reacted to the criticism saying there are many products named Go. Well... that's a 2-way street. If there are many products called Go then why picking that name in particular?
The rest of your criticism may be valid, but I would think that this part is obvious:
(1) It's a word.
(2) It's short.
(3) It resembles Google.
Sounds like gojson[0] would make your life a lot easier - it automatically generates the struct definitions for you.
This feels so much easier to work with than untyped scripting languages where I basically get a hash bag and read values out ad-hoc, checking what they are as I go.
I don't think I'm alone. I need some hugs.
Go sounds like Swift, strongly type compiled languages. Go has better concurrency features and likely compiles faster (I mean anything has to compile faster than Swift).
Swift still seems to have better, faster garbage collection, better language features such as generics, and optionals make error handling and writing safe code much easier.
But Swift doesn't have the community and infrastructure around server development that Go does. I think I'm giving Go a go next project.
I honestly don’t think Go does enough to it to make it worth using over something like JavaScript. You still have to write unit tests and integration tests. It’s strongly typed, sure, but it’s type system isn’t robust and doesnt really help you that much, and it just feels.. outdated. Every other line of code is “if err != nil”. Nil pointer exceptions are.. still a thing. Yuck.
Typescript has a far more expressive type system than Go.
The usual complaints: error handling and lack of generics. But both TypeScript and Swift do a better job in those areas. If Swift had a better story for async then I'd want to write everything in it. As you say, the server-side community just isn't there yet, so it's Typescript for me.
It's better than plain JS, but if valuearb really wants to experience type saftey, they should look somewhere other than Golang. Swift, which they also brought up, would be a much better choice.
Setting the scale for language comparison to C (or Python) is setting the bar pretty low. There are so much better languages out there.
I'm struggling to find a need for this. Flags define behavior, who cares if the behavior is explicit or implied from inaction?
> id = flag.Int64("id", -1, "ID of the thing I want")
Obviously that doesn't work for booleans, but you could take the boolean input as a string and then use strconv.ParseBool
It has it's downsides but I love it despite those, errors could be better but it's mostly fine and I'd love some generics so I could optimize my storage structures (though by using a backing array and referencing indices helps a lot)
I am not experienced enough with go, but I would say the same. Not better maybe, but the modern C.