232 points · by ibobev · 4y ago · 286 comments
It's pretty annoying that golang embraces static and functional patterns in its core, but it doesn't even have map/filter/reduce/forEach as generic implementations for all data types.
The lack of a "new" keyword and default values for struct's property syntax is also pretty annoying. Let alone the "hack" with annotations for decoding/encoding everywhere, just so that you can use reflect API in the encoder implementations.
For loop fatigue in golang makes it so unreadable in practice, and leads everybody to offloading manipulation of arrays/slices to helper methods, just to have the for loop there.
The library that fixes this as good as possible with generics is the "lo" library (inspired by lodash) [1]. It's worth taking a look at it if you're curious how to implement it for your structs.
Generics landed in the latest stable version, 4 months ago. Before doing too many too early additions in the stdlib they want to observe how generics are used in the wild. I don't have the link handy, but it was mentioned in one of the generics discussions (issue on GitHub).
In these cases (another case was error wrapping prior Go 1.13) they start with experimental libraries in `golang.org/x/exp/...`, which they did here as well:
https://pkg.go.dev/golang.org/x/exp/slices
https://pkg.go.dev/golang.org/x/exp/maps
So while the stdlib doesn't have the functions you're looking for yet, this might change over time.
The rationale can be found here:
Go's paradigm of making the zero-value something meaningful is great, but it isn't always viable unfortunately. Even in the stdlib there are a couple of structs where you're better off changing those values.
I think that parent probably refers to the lack of something like this:
x := new MyType
Go takes away type system fidget spinners and leave devs with nothing to do but the actual job, which they hate, and thus they hate Go.
The majority of developers I work with are only aware of the success paths of their code. That means we’re knee deep in exception corpses because they avoided doing part of their job.
Go makes them deal with it.
However, repetition can introduce bugs, too, for example a very common mistake is to write this:
if err != nil {
return nil
}
instead of this: if err != nil {
return err
}
which is pretty serious because you essentially ignore the error.This particular pattern is so common your brain often ends up completely skipping it and it's pretty hard to detect during code review.
Rust, Haskell, Kotlin, yes. They force you to consider the error path.
Go makes it all too easy to just ignore errors and produce crashy code.
As golang has no instanceof or typeof keyword, you practically you cannot use a method that uses multiple types as arguments without having to use the reflect API, just to have an if/else branch on what to do with that argument.
The things that I mentioned are from another point of view where language designers and implementers decided to implement the interactions with their data types in a different way, by providing overloadable methods with different function signatures for the same function name whereas in golang everything must be "namespaced" in a sub sub sub package.
Good luck finding the right methodology where to sort in a method that can handle two different structs. If they're nested it's not even possible cause golang's dependency resolver doesn't allow cyclic dependencies.
Parsing html5 in golang is a nightmare, and I've realized that this language is not made for such a use case.
You don't have to use reflection, there are typecasts:
"value, ok := arg.(MyType)"
You can also switch on a type. How is it different from instanceof in practice?
Seems like a fake problem that one would only feel if they buy too much into functional programming.
Some ideas in fuctional programming are useful, but overall, for loops are much more preferable to map/filter/reduce.
For loops are much more easily amenable to incremental changes.
"reduce" is particularly bad. It obfuscates control flow for no benefit at all.
I strongly disagree on this one. A .map or a .filter are clear and concise while filtering or mapping, particularly in a streaming situation where you're only iterating the collection once.
You can trivially write code using this paradigm that's easily readable, performant, and takes up a handful of lines that would take dozens in Go.
If you look at the programming language landscape I think one wouldn't be unreasonable in pointing out that very little is understood in terms of how you go from good ideas to widely adopted language.
What affects reality is important.
Industry language designers are trying to make their users more productive enough to justify the cost to design and build the language. An industry language that doesn't have enough users and doesn't make those users' lives better enough to offset the salaries of the language team is a losing proposition and a bad language.
Academics are trying to publish papers on novel ideas. A language that cured cancer would be considered a bad language if someone had already designed a language that cured cancer the prior year.
These incentive structures a somewhat opposed: the easiest way to make a language easier to adopt is to make it more familiar and less novel. But they are somewhat aligned as well. A language with no new ideas can't be any better than the languages before it.
So there is a natural diffusion process where academia explores the frontier of weird language ideas. Many don't pan out. All of them are weird and unapproachable when they first appear. The ideas worth keeping stick around. Eventually an industry language will add a dollop of those novel ideas and surround them with a familiar framework so that users can actually absorb and use the thing.
Interesting choice of words: my guess is that the great languages Academia cook-up scale poorly on code bases which receive tens of updates per day (let alone hundreds or thousands). There's usually a huge difference between industrial tools and artisanal ones.
> Full rebuild of the Reason part of the codebase is ~2s (a few hundreds of files), incremental build (the norm) is <100ms on average. The BuckleScript author estimates that the build system should scale to a few hundred thousands files in the current condition.
> Messenger used to receive bugs reports on a daily basis; since the introduction of Reason, there have been a total of 10 bugs (that's during the whole year, not per week)! *
> Most of the messenger core team's new features are now developed in Reason. Dozens of massive refactors while iterating on ReasonReact. Refactoring speed went from days to hours to dozens of minutes. I don't think we've caused more than a few bugs during the process (counted toward the total number of bugs).
In a high-velocity codebase, modularity is the name of the game. And you will be hard-pressed to find languages outside the ML family which are that good at modularity. OCaml is just about the only industrial-ready language in this space.
[1] https://reasonml.github.io/blog/2017/09/08/messenger-50-reas...
At the time when that post was written (including the "no bugs") the web version would continuously fail in the simplest of tasks while having a fraction of the features of the app version.
Why would they? Many are designed meticulously to address the issues industry has. I've worked on a multi-million line Haskell code base in a financial institution and it scaled better than e.g. C++ or Python. In 30 years time, I'm sure the industry will be extolling the virtues of algebraic data types, purity, immutability and referential transparency.
> In 30 years time, I'm sure the industry will be extolling the virtues of algebraic data types, purity, immutability and referential transparency.
There are plenty of industrial languages with algebraic data types and immutability. Not as many as I would like with purity but I doubt it will take 30 years.
It's really hard to know what you are doing right or wrong when you are writing a large program. There are no guidelines for proper layout, logging, and error checking practices, and no matter what you do, it's verbose and error-prone (more code = more bugs). It's all DIY. I referred to HashiCorp code to see how they do things, for example.
As someone here said once - Go is basically improved C, after snoozing through four decades of language development. On one hand Go lets you go wild, and on the other it imposes rules that are seemingly arbitrary, like enforced naming conventions, but only in certain places.
Go is odd in that its proponents seem to flatly deny any of the very reasonable criticisms levied against it. And they continue to do so right up until the moment that the language authors finally address them.
I feel, programming too often lost productivity with quite a few modern languages. Go brings that back and adds a good amount of modern features, but doesn't get too much distracted by them.
So the definition of success is that Go makes those people productive. If you give these fresh hires C++, now everything is on fire and even experienced people sent in to extinguish the flames end up just saying evacuate the entire site and let it burn itself out because that will be cheaper than diagnosing what's wrong.
This goal means some choices Go makes which I don't like seem more respectable. For example Go specifically warns you not to get clever. This is sound advice for a 22 year old new programmer who still probably thinks "Romeo and Juliet" is about true love, but it'd be very frustrating if you were trying to squeeze the last drops of performance juice out of a system. The answer from Google's point of view is that Go is the wrong language in that case and it's time to rewrite.
Also, it would be interesting to hear your take on why you think languages that are, as you say, from "a sound theoretical foundation" tend to struggle with adoption?
Could it be that you fail to take into account that the things that make a language appealing in an academic sense may not make the language a particularly practical language?
Wide adoption means certain academy-hostile rules: backwards compatibility, a lot of user pressure towards certain directions, etc. Academics need freedom, and adoption is not about freedom.
ADA may be up your alley. it was fully designed and specified before a single line was written.
Each time we added more advanced typing to new sections of the system, new bugs and security issues were found. At the end there were over 100 places that were being used incorrectly. This is something that linters and the library itself failed to catch for years, but with proper typing we got there.
I've found Dart to be perfectly adequate. Like Go it doesn't try to be overly clever; unlike Go it doesn't consider verbosity to be a feature, and believes you're capable of using advanced techniques like ternary expressions responsibly.
interface Numeric<T> {
T zero();
T add(T a, T b);
}
static <T> T sum(Numeric<T> n, T[] v) {
T summer = n.zero();
for (int k = 0; k < v.length; k++) {
summer = n.add(summer, v[k]);
}
return summer;
}On the other hand C# offers "real" generics and you can use almost exactly the code that you wrote (generic syntax is slightly different).
[1] https://blogs.oracle.com/javamagazine/post/what-are-they-bui...
My wishlist for Java is for null to be illegal for all types unless they are encoded as nullable such as `T?`.
Until then, I just use Kotlin and/or Scala when I require JVM.
Generics are viral. When you make something generic, you often have to make the things that touch or contain it generic, too.
Generics also create tight coupling. When you change the definition of a generic interface/class, you'll need to update your usage across the codebase. As opposed to, say, adding a new field to a class, that can be safely ignored anywhere it isn't used.
When this component you're updating is highly connected to other parts of your code, perhaps add another generic parameter to it, it completely explodes and you have to jump all around your codebase adding generics.
The kicker is that you may be updating components which are themselves generic and highly connected, setting off secondary explosions. Pretty soon you're throwing that codebase out, starting over, and swearing to yourself that you'll never touch generics again.
My advice is to assume generics are a premature abstraction until you've exhausted what you can do with more concrete approaches.
Where is `zero()` defined? Why does a `Numeric` have a function to `add` two numbers? Shouldn't you add a single number to a numeric? What is the relationship between `<T>` and `Numeric<T>`? I thought `T` was a `Numeric`?
Edit: Upon closer inspection, I kind of get what's going on. But it's really cryptic for something that should be simple to express.
It's defined by whatever implements the interface.
> Why does a `Numeric` have a function to `add` two numbers?
Because Java doesn't have user-defined operator overloading, so if you want to add stuff in a generic fashion you can't rely on `+`.
> Shouldn't you add a single number to a numeric? What is the relationship between `<T>` and `Numeric<T>`? I thought `T` was a `Numeric`?
`Numeric` doesn't contain data, it just defines operations on numbers. So `Numeric<Integer>` would define operations on `int`s, `Numeric<BigInteger>` would define operations on `BigInteger`s, etc.
There are probably other reasons to do this that I'm forgetting, but off the top of my head,
1. You can implement `Numeric<T>` or `Comparator<T>` for types `T` that come from a library that you can't change (so can't make T implement an interface that the library author didn't implement), or where you don't want to introduce a dependency (you could have a type class `JsonDecoder[T]` that comes from a library, and you don't want the library with your T to introduce a dependency on the json library).
2. You can have more than 1 implementation for a given T. For JSON decoders/validators, you might provide a decoder which bails out on the first error, or one which tries to continue reading fields so it can return all errors (field X was a string, expected number. Field Y was expected to be >= 1024, etc.). For comparators, you might have a `.reversed` function to easily make a comparator that sorts in reverse order. etc.
Basically I'm encoding this approach in Java.
There's something like a cognitive bias that makes me leary of genetics (in any language). Once you have some cross cutting feature, generics or object orientation, or in functional programming, those functions of type 'a->'a, or assembly language address modes, people get bogged down by trying to make everything in their work generic or object oriented or "orthogonal". Lemire's example is relevant to his topic, but it could be a poster child if someone else did it. They need to sum an array of int. So they spend 4 days getting a function and a generic type that can sum every numerical type, rather than 15 minutes to sum int arrays.
What's this called?
More likely they install a 3rd party generic sum function and don't have to write their own at all. Well, in the case of a sum function it's probably only 15 minutes to write to generic version, and there may even be one in the standard library. But consider something like a concurrent hash map. In Rust, You just `cargo add dashmap` and you have one that works with any type that works with a regular hashmap. This isn't possible without generics.
> More likely they install a 3rd party generic sum function and don't have to write their own at all. Well, in the case of a sum function it's probably only 15 minutes to write to generic version
I'm not sure "sum over an array of int" is a great "simple" example - how do you guarantee that the result can fit in an int?
This is (one reason) why Julia implemented a full, scheme-style, numeric tower right in the core language.
Sure there are some examples where you can sum N Mbit numbers into an Mbit number, and either want overflow, or is somehow "confident" things will fit. But in general it's just lazy "no one will ever have such a large shopping cart"-design...
What's the result of adding two i32 then? Is it an i64? Doesn't the accumulator need to get wider on some additions, since adding an i64 to an i32 might also overflow an i64?
The blub paradox https://wiki.c2.com/?BlubParadox
This is the essence of the blub paradox, thinking that people who use a feature are simply misusing it, after all in blub you don't have generics and things are fine. They're just making things more complicated than they need to be.
The blub programmer isn't necessarily smug, they just make excuses to dismiss more powerful language features that they are not sufficiently familiar with.
template<class T>
T sum(T* x, size_t size)
{
T acc = 0;
for(size_t i = 0; i < size; ++i)
acc += x[i];
return acc;
}Took me five minutes, not four days…
Polymorphism. But note that there is only one function of type 'a->'a for all 'a, and that's the identity function.
def nitpick(x): throw “foo”
technically a partial function, or you could say that every function is really of the type A -> Exception \/ A
func sum[Number](nums: openArray[Number]): Number =
for num in nums:
result += num
Took about a minute.> So, at least in this one instance,
Yeah, one example which is not even that useful. It might be cherry-picked for all I know.
The problem is not with the implementation of generics per se, the problems is numeric types in those languages is a really leaky abstraction.
It's all well and good to generalize basic containers and functions (good, in fact), but I wish the language was better at inferring types.
I'm sure this is something that will improve with time, but a bit after generics were released, I tried to build a type-safe language evaluator in Go using generics and found them lacking the kind of type-narrowing necessary for fully-generic architecture.
Short write-up of my conundrum on SO, if anyone is interested: https://stackoverflow.com/questions/71955121/how-to-type-swi...
TypeScript has me spoiled. :)
https://planetscale.com/blog/generics-can-make-your-go-code-...
If you want a sophisticated type system with a language they complied to native code then use Swift or Rust.
I personally think it is good to have some choice in complexity level and that at least one language, Go, tries to carve out a niche in simplicity.
I am only barely convinced that generics was the right choice for Go.
Interestingly, it looks like Rust (and C via clang) both generate something like the following as their one-at-a-time main loop:
.LBB5_14: addl (%rcx), %eax addq $4, %rcx cmpq %rdx, %rcx jne .LBB5_14
It's one fewer instruction than the Go version (because it has combined the MOV and the ADD), although I don't know whether that would actually result in higher performance.
I say their "one-at-a-time" main loop, because they actually seem to generate lots of code to try to take advantage of AVX or AVX2 to add 4 or 8 values at a time if available and the array is long enough!
It might be cheating, but summing an iterator over numbers is built-in to Rust, so summing an array is just: v.iter().sum()
The fun thing with this is that it's not just generic over number types, it's also generic over any type of iterator, so I can even use it to sum over the values in a HashMap: hashmap.values().sum()
I'd expect a CS professor to be able to add a little more rigor in a blog post but I guess everyone is losing patience to read and write these days, even for the supposedly erudite.
Someone submitted and people liked it, and it ends up in HN front page.
All I am saying, please don't put pressure on random blog writers. You can criticize the content without saying "CS professor can be more rigor".
https://go101.org/generics/888-the-status-quo-of-go-custom-g...
I mean, my cousin still in high school can do better than that...
Of course there is going to be an impedance mismatch. What makes people important, effective and useful isn't what silly snobbery they use to put other people down, but whether they can effectively communicate their ideas to the audience.
https://planetscale.com/blog/generics-can-make-your-go-code-... is a much more in depth dive into how Go's generics work that shows some of the easy cases, like this article, but also the more general cases.
???
By the time it gets to the JIT, java generics have long since been erased.
Java's generic classes run at the same speed as everything else, because there's no actual generics there.
(Although I'd be very surprised if this doesn't change in the near future: https://openjdk.org/jeps/8261529.)
Five years from now, Go will still exist. The implementation of generics in that future version of Go is likely to be much faster and better than what we currently have.
Put a different way, "Generics are slow in Go v1.18"
I would rather call it cherry-picking if one avoided covering such a case to make Java look good. Seems like a pretty obvious problem to me.
Handling basic number types is pretty bread and butter.
Java is way worse than Go on that aspect.
The reasons are explained here: https://go.googlesource.com/proposal/+/refs/heads/master/des... but the point is, you can have this in Java, but not in Go.
You look at something like the Reader and Writer interfaces and there are very few methods. The Go approach is to put more functionality in free functions such as fmt.Fprintf which allows more code reuse across multiple types.
In fact I view the heavy Java use of methods as an anti-pattern.
Of course, type erasure isn't the actual culprit in that case, but once you don't do it, it gets very tempting to allow pattern matching on type parameters...
And people wonder why we complain about C++..
So this excuses the awful Java genetic how? "It smells like sewage in the basement because the basement is full of sewage." In addition, generics over primitive/stack/value types (including mathematical operators) is working just fine in the latest iteration of C#.
If generics had had to actually support ArrayList<int>, they would have required significant changes to how ArrayList is stored in memory, and to how a lot functions which work with generic types are actually compiled. Instead, Java has the easy path in the implementation: since everything only works with reference types, there's no need for multiple copies of a function to work with different types.
Of course, this means that sum<Integer>(new Integer[1000000]) is going to be orders of magnitude slower than sumInts(new int[1000000]).
though this can be solved either with types, as mentioned in another comment (https://news.ycombinator.com/item?id=32029871), or simply by providing the sum operation:
static <T extends Number> T sum(T[] v, BinaryOperator<T> adder) {
T summer = v[0];
for (int i = 1; i < v.length; i++) {
summer = adder.apply(summer, v[i]);
}
return summer;
}
Float[] ft = { 0f, 1f, 2f, 3f };
// which can also be written as
// `float z = sum(ft, Float::sum);`
float z = sum(ft, (x, y) -> x + y);To get a comprehensive understanding of the current Go custom generics, please read: https://go101.org/generics/101.html
But insulting a free knowledge sharing article while posting your own site which is laden with 'buy buy buy' is rather poor taste, IMO.
"insulting"? That is a too heavy word.
I guess I’ll wait until the full review then
1. decided generics is not needed
2. went on for a decade
3. implemented a version of it that is not performance-sensitive
3.5. $$ by googleThe FAQ on the official site already back in 2013 (I couldn't find an earlier snapshot on webarchive) stated they were open to adding generics but weren't sure how to properly design/implement them without overcomplicating the language, citing also other priorities.
>implemented a version of it that is not performance-sensitive
It's less performant than the ideal but it's a tradeoff to avoid exponential code bloat found in C++. In our large C++ project which extensively used templated boost.signals the code bloat from using templates alone added a whopping 200 MB of machine code which we were able to shed off by switching to our in-house library. IIRC C# uses an approach similar to Go to share generated code with some type-specific conditions at runtime (at least Mono I remember shared generic code for all reference types)
#3: they’ve clearly said that they’re doing “get it right before you make it fast”.
What is often claimed instead, and is indeed false, is that they believed generics should not exist in Go. This is a position that many Go proponents take, but the designers of the language never did.
1. go generics do this one thing 2. therefore they are good
Go generics are better than no generics but they're still limited, and that frustrates me.
https://stackoverflow.com/a/498329/729738
.Net generics do have same issues mentioned in the article
https://github.com/dotnet/csharplang/issues/4436 https://devblogs.microsoft.com/dotnet/dotnet-7-generic-math/
Never understoon why Generics where subject of a holywar in go community. It's an important nad basic feature these days