by jaytaylor · 4y ago · 0 comments
Do you think Generics will be an overall win for the Go language, or will they be overused / end up making code harder to read / harder reason about?
I kind of hate looking at Go code containing generics. What previously was elegant and easy on the eyes is now annoying and muddled by the additional layer of abstraction. I'm saying this with sadness, as someone who fell in love with Go back in 2012 and still writes it at least weekly.
Is it a better bet to move on and go full Rust, rather than bother with wherever the goggle golang train is headed?
p.s. Even though code generation is [also] annoying and perhaps not ideal, I've rarely needed to use it and kind of liked that it was inconvenient - forcing me to think about problems differently. Certainly some problems will benefit from the addition of generics, but is it really enough to justify the added complexity? I wonder if this is a case of tragedy due to vocal minority.
p.p.s. Generics in other languages like Java or Scala seem fine, as they are "kitchen sink"-style "all things to all people" languages. Such behemoths are nearly always clunkier and less easy to read than pre-generics Golang.
Ecosystem aside, with Rust you'll get far better language design (generics fully integrated with everything (stdlib, consts, all libraries), sane error handling, sane dependency management, no "any" type, editions, and more. More complexity too though.
> Certainly some problems will benefit from the addition of generics, but is it really enough to justify the added complexity?
Coming from languages that have them, it's just hard to take Golang seriously, where every library either ditches type safety (more runtime errors I wouldn't have with other language), or forces you to copy-paste code just because you need support for some new type (more boilerplate to maintain == more errors). Or reinvents generics with code generation and aboriginal characters.
Once you start using generics, they really aren't complex.
Some people judge the language on their ability to get work done with it.
I get generics, but they really don't come up in daily use with the tasks where I use Go. Yes, it would be nice for writing some libraries but you're going through a laundry list of Rust features which don't hamper my ability to get work done at all.
I even like Rust, but if I'm going to write a worker that will read from a queue, do a transformation and write to a few more queues/services upon completion, Go just works and the turn around time is far better than Rust. It's like was Perl was for Unix, but for the cloud instead.
I wrote a bunch of Rust, Scala, Haskell, but I still greatly prefer Go, even without generics.
I am very happy with the generic container libraries I'll get with generics, but I hope people won't try to be too clever (as they usually do). So far, Go is a language that just rules out a lot of bikeshedding, which I very much appreciate. We'll see how that evolves.
I do think premature or wrong abstractions are a much bigger and widespread problem than a lack of abstraction.
Also, I really like Go's error handling, it results in error messages in Go projects usually being top-notch (because of explicit handling and wrapping which includes relevant context and human-readable messages).
I remember listening to a podcast about C++, and the guest explained how after working with C++ for about five years, they still encountered aspects of the language that surprised them on a regular basis (to be fair, though, that was before C++11). To me, Go just clicks in way few languages did.
While I applaud the focus on simplicity, I found it simply transfers that burden to the programmer (I have to loop over a map to clear it...really?). Every single "lack of" feature in Go (has nil, no sum type errors, no pattern matching, etc.) is in Rust which gives me endless freedom to express safe, correct programs. I suppose language choice is highly individual, but it still perplexes me as to what people see in Go over Rust.
I sort of understand this argument, but I can't really imagine defining queue as something else then <T> wait_for_item() -> T. I've been writing Python for to long to know that wait_for_item() -> any will backfire in production eventually and I don't want that. At some scale (both in code size and amount and scope of dependencies) those problems just become too serious and too common to not have language that deals with that. And Go is way too popular for people to limit its use only for the cases where it currently works.
A specific queue is typically well defined and has a struct in/out.
There are times when I've wanted arbitrarily nested JSON that doesn't map into structs very well, but it is uncommon enough.
Since the inception of async/await in Rust, it is incredibly quick to whip something like that up. The slowest part might even be the time it takes to compile. Maybe that's what you were referring to?
Really? Safety and correctness aren't relevant for you? Then why even bother with go instead of Python or a Lisp?
For me it's crucial that a programming language contains tools that allow me to definitely rule out as many errors as possible. A powerful (and sound) typesystem does just that.
If you want to definitely rule out as many errors as possible, dependently typed languages are the state of the art, allowing you to write a sort function that will fail to compile if it returns a list that isn't sorted (eg,https://dafoster.net/articles/2015/02/27/proof-terms-in-idri..., or https://www.twanvl.nl/blog/agda/sorting).
After all, if you can't even prove basic properties about your code from your language, like array accesses being within bounds, are you really using all possible tools to rule out errors at your disposal?
> Really? Safety and correctness aren't relevant for you? Then why even bother with go instead of Python or a Lisp?
A charitable reading of the GP would be that "safety and correctness" would be included in "getting work done", in amounts that are appropriate to the work in question. Your interpretation is... less than charitable.
Perl and Go both have the kind of long-term language stability that I value above all.
But Go offers excellent concurrency, networking baked-in, and now even fuzzing.
I value maintenability (type safety helps prevent unintended consequences) and readability (Haskell and Clojure are out).
Go w/generics falls very short IMO, expressibility, type safety and poor null handling all rule it out as a reasonable stand-in for Rust.
That's why languages like JS/TS, Haskell, Elixir, OCaml (which is way more modern than Go), ... exist and are used.
If only its ecosystem was more platform agnostic.
If you continue to disagree with me, please be specific about what operation Go permits on interface{} values that you consider type-unsafe.
I imagine the rebuttal to this is that you could always just manually `unwrap` the `Option` that is returned by the downcast methods in Rust, but I pretty strongly feel that adding explicit syntax for this type of unsafe cast normalizes it to an extent that having an `unwrap` method on a generic Option type doesn't remotely approach. It would be quite a stretch to argue that having the `unwrap` method on Option is explicitly a endorsement on unwrapping on the downcast methods given that Option is used for far more than just that (and especially given the huge amount of stigma that using `unwrap` gets in the community, which is mostly fair but sometimes goes a little overboard). On the other hand, having specific syntax that is used for unsafe casts and nothing else is a pretty explicit argument that it should be done sometimes, or else it wouldn't be in the language at all. Go could pretty easily have gone the route they did with map lookups and had the unsafe casts return two values, the latter of which is a boolean indicating success or failure (and in the cast of `false` being returned, the former value would just be the zero value for the output type), and the fact that this wasn't done means that ergonomics was prioritized over safety.
Rust has a mind-boggling overhead, for many reasons (and I'm not talking about the borrow checker, which I think one gets used to after some time), even if the language itself is consistent and ergonomic (within the intended constraints).
To me, they have very different use cases - one will definitely know when Rust is required or it's an appropriate pick. For the rest, Go is fine. I think that those who put them on the same basket, haven't really used one of them.
Regarding systems programming, my opinion is that they require the lack of a runtime (not just because of the performance, but also, for the framework(s) written with low-level primitives in mind), but this is arguable (in particular, there's no clearcut definition of what systems programming is).
I'm not saying everyone would fit in that camp and it is a harder language to get started in for sure, but I think the borrow checker scares away too many people. It is a learning curve, but when it clicks, you will realize that every language has ownership and borrowing... you just didn't realize it because the GC allowed you to be sloppy about it. Once you do, it makes you a better programmer (just like coding in Haskell does).
Due to ability to work without stdlib, Rust is system language in a sense Go never will be, to the point Go authors withdrawn this definition.
> Is Rust really a suitable replacement for Go?
It depends on your requirements for the ecosystem. If you need compatibility with Go or Go libraries, than it's not a replacement.
Libraries and support aside, any program written in Go can be written in Rust (and going back to nostdlib, many programs written in Rust cannot be written in Go). If you have required libraries, I'd say it can be written comparably quickly and easy. For example you can have web service returning hello world in 10 lines of code or so in either.
They are popular in different circles, but that is mostly not related to technical abilities. For 99% of of applications, you could pick either one.
This is a good direction for Go, which will either lead to Go having a better ecosystem, or remove ideological barriers from people keeping on using Go.
Tell me you’ve never used Go without telling me you’ve never used Go.
Here's my $0.02 from a java background. There will be cases where someone overuses generics. That happen pretty much every time a new language feature lands in any language.
However, my expectation is that like java, you will see Go generics in general practice only come up when dealing with things like collections. Once the community settles and stops trying to use generics as a meta-programming language, they will become pretty boring (which is what you want).
From a readability standpoint, IMO, generics in Java don't really have a negative impact on readability. Sure, you'll get the random `Map<Map<String, Object>, Object>`... but most people see that as the anti-pattern it is.
In short, I'm guessing they'll be a win.
It's that "correct by accident" part that's hard to have both safe and performant without generics.
I'm pretty disappointed to see generics introduced into the language and every example I've seen feels completely unreadable to me compared to pre-generics implementations.
To be clear, it has never been the case that the Golang authors were 100% against generics. It has always been their position that the implementation needed to be good enough to make the trade-offs worthwhile. I just don't think they chose the right trade-offs.
That's pretty surprising to me. Have you never had to implement marshalers for unknown types and such? I have had to implement things like json.Marshal and json.Unmarshal for different encodings dozens of times in my Go tenure. I have had to use reflection a lot. I have had to deserialize into map[string]interface{} to handle ambiguous situations at runtime a lot. Have you never even had to wrap or build your own Printf equivalents that accept interface{}? No loggers? No custom containers? None of that which operates on unknown types?
I see use of interface{} all over the vast majority of Go projects. I think your experience may be atypical.
In spite of that, it's unlikely that I've written implementations where using interface{} would be easier to read and reason about than not using interface{}. And the experience of the author whose blog post we're commenting on tracks with mine: "In my 5+ years working in Go, I can probably count on one hand the number of times that I felt like I really needed generics." I can too, just without using any fingers :-)
I expect well-curated libraries to come about that will really simplify some otherwise difficult problems for people (e.g. task/object pooling). I'm even toying with a futures impl at https://github.com/cretz/fut, but I wouldn't use it in place of channels in most cases.
Something I worry about is if I'm getting too jaded. You really think things are different elsewhere, but then you see that we all eat the same shit sandwhich.
That code would never have to be written if someone just used their brain before switching their integer IDs to string GUIDs. Bless your soul but I wish we didn't have to resort to such things. Some things code can't fix.
At most I have used non-empty interfaces to solve very few number of issues (countable on one hand). I have never needed interface{}.
Funny you say that because for me that's the one use case I have for generics.
(edit: why the hell am I getting downvoted for posting a fact? I wasn't offensive, argumentative, etc. Just citing one example I've run into where generics would help me personally)
Perhaps a Go 2 if they ever get there could be a generic std lib rewrite, largely transparent to the end user, with some minor incompatibilities allowed and lots of stuff rewritten behind the scenes. They could remove a few ugly corners in the stdlib naming specific types by using generics, add a few more container types perhaps, deprecate some old stuff and move it out.
From https://itnext.io/generics-in-golang-1-18-no-need-to-write-m...
Here's a fun one I stumbled on: How do you implement a PUT endpoint where a missing JSON value is treated different than a null JSON value? This ends up being very difficult and requires a boilerplate wrapper type for every single type you might accept. It's even worse when you start accepting slices or maps, or slices of maps...
These are areas where generics will help me a lot.
> How do I disable static typing for this statically typed language?
I have sympathy for your struggles -- I've been there. But fundamentally this always ends up being a problem of putting a square peg into a round hole.
I don't expect most folks to agree with this take, but I have the utmost faith it'll age well.
If you don't believe me now, set a reminder for ten years and see how we feel about JSON and GraphQL.
Ideally this is all transparent, and programmers can stop wasting their lives reimplementing this stuff again and again and again, but even if programmers don't waste their time reimplementing it, computers will spend a decent amount of time running it, at least where there is more than one process / machine / whatever in question and therefore untrusted boundaries.
What on earth does dealing with untrusted inputs have to do with anything?
Tbf that’s a pain in the ass everywhere unless you’re reifying it as a map (so manipulating a json dom).
Iirc in rust the “complete” way to do this for a struct (as opposed to a map) with serde require two options and a bespoke deserializer.
The Go answer is a struct that contains an IsDefined boolean (i.e. your first option), and a pointer-to-value (i.e. your second option.)
This is fine if you need it, but having to write this same logic over and over again for every type gets old... especially if your validators are tied to your types (i.e. a type per field.)
Oh I’m not blaming you, sorry if it came across that way. I’m aware of the issue because i’ve been hit by the exact same (hence having been made aware of the rust workaround), can’t say I was a happy camper.
If you don't like generics you shouldn't use Rust. You can't escape them in Rust. The designers repeated the mistake of C++ and made it a language feature kitchen sink. It's an unholy mess. You'll find yourself constantly fighting the borrow checker. Type signatures are littered with lifetime annotations. The type system is Turing complete because they didn't analyze it before implementing it. Go's generics were formally validated [1]. Rust's compile time is slow, and the 'async' story is sad. Async functions are colored and infect everything.
In the beginning, yes, this is true. But most people learn within a month or two which design patterns lead to problems with the borrow checker and which work smoothly, and often this knowledge translates to good design in languages like C and C++ as well.
If you're fighting the borrow checker in Rust, you'd probably have been fighting segfaults and use-after-free in C / C++. I'd rather spend 30 minutes fighting the borrow checker than spend 4 hours digging around in Valgrind.
> Type signatures are littered with lifetime annotations.
You cannot avoid the concept of lifetimes, without a garbage collector. If you don't want garbage collection, you have to deal with them.
Having explicit lifetime annotations in the code is _vastly_ better than trying to track the lifetimes in your head from scratch every time.
That is in my ( admittedly limited) experience just not true. There's plenty of things that are perfectly safe that the borrow checker just doesn't understand.
The borrow checker can prove that a subset of things is safe. But the borrow checker being unable to prove something doesn't mean it's not safe.
The borrow checker forces you to write in the very narrow subset of code paradigms it can understand. When it fails to compile, it doesn't mean it's wrong: it means that it can't prove that it's correct, which is a completely different statement.
There's nothing wrong with either approach, they just have different trade-offs because their goals are different. Rust's approach will sometimes push complexity onto the programmer to handle. But it can be made to perform better and more predictably than the Go equivalent. This might not matter if you're not pushing the performance envelope, but if you are, Rust makes that possible in a way that Go simply doesn't. You'd never want to write code using goroutines for an embedded device with limited CPU/memory, but Rust's async is already proving useful for these sorts of projects.
However if you can tolerate the performance overhead that Go imposes, giving the programmer a simpler mental model can easily be worthwhile. Technology is all about trade-offs and you have to choose the right tool for the job.
If you think C++ is a beautiful well deigned language, then I am sure you will not have issues with Rust either.
* not just toy examples
Personally I would discourage overuse of generics in an application codebase as I’d discourage overuse of interfaces, concurrency or channels - they have their place in certain areas (for generics e.g. collections, orms - mostly in library code) but most of the time simply aren’t required.
I don't want to read through a heavily templated, generic code base when concrete, simple types will do. Go is so easy to read and reason about that I'm genuinely afraid of any change which could affect that.
The best advertisement for avoiding generics in Go despite their availability is the fact that they won't appear in the standard library for some time, and that the language maintainers believe it will take years to understand how to use them appropriately.
On the positive side, now Either/Try-like composable types are possible. So even if they insist on not having exceptions they could clean up error processing.
I second that sentiment, but I would have to look into the specifics. Generics ala Java aren't really that attractive when Rust mainstreams ML-style polymorphism with Haskell-style overloading.
First, the Go community mainly comprises people who love simplicity and got accustomed to it. I imagine most people who want to go overboard with generics will stay with languages that let them go way more overboard.
Second, and more importantly, there's no method parameterization, which saves us from monadland.
IMHO Go generics are simple and useful, particularly for container libraries. They are fairly readable, unlike template programming and macros in other languages. Together with the any type alias for interface{} they will make code more readable.
I do hope that Go stays at version 1, though, or that it at least takes a long time to add new substantial features and get version 2. Slow change is one of the many advantages of Go and I'd rather see them improve the compiler in hidden ways.
Will it be nice with generics for carefully crafted and cherry-picked use-cases? Absolutely.
Will it make the average large codebase less readable after a dozen coders have been doing their own cleverness with generics 3-5 years down the line? In my experience, most definitely.
Of those two, I'm much more afraid of working with the latter than missing out on the former.
It sometimes feel like we as devs have a habit of optimizing for the individual dev's convenience (not to mention what's fun) rather than for the collective effort's best interest - like the long-term maintainability/coherency of the code base. To some extent I assume that's just being human, but in other professions I think it would be seen as a bit lazy and thus more stigmatized.
A bunch of people will write libraries that utilize generics in some way that's not very orthogonal to the rest of the Go ecosystem. They'll put these libraries out as quickly as possible, because they want a first-mover advantage in picking up adoption. A handful of people will take their time and learn how to utilize generics in a way that is native to Go. Eventually those people come out of the woodwork, and it turns out that utilizing generics in Go looks different than it looked in some other language, so a lot of the early assumptions about how to use them were wrong. A bunch of those early libraries turned out to be badly designed once actually deployed into the real world, so they fade out of use as their problem domains get written by newer libraries that utilize generics in a manner more orthogonal to the rest of the Go ecosystem. A few of those libraries picked up significant market share, and maybe a startup has shipped stuff that generates revenue with those libraries, so they fund those projects, which continue to exist as a result of pure inertia. So now you have some big libraries written in like ... March of 2022, which are just bad, but people keep promoting them because they have a vested interest in doing so, but the ecosystem at large moves on, and by late 2022, generics will fit in very nicely with Go and not complicate things in an unnatural way. I'm wary of what's coming in the short term, but optimistic of what's coming in the long term as a result of this change.
I'd go for Rust tbh. I think it's a much more coherent language.
I like Go because of the tooling and simplicity of the language, it's easy to learn and explain.
Rust has the borrow checker has a corner stone. The concept mutability and references is easier to understand if you are coming from the c/c++ side of things
While generics moves Go in the direction of rocket science, it feels like this is solving a problem I always have.
If you want to unnecessarily encumber your mind with trivial but tedious memory management puzzles, then choose Rust.
> I’m not sure that most Go developers will be using generics daily, but it’s nice to know that they exist if we need them.
Most people won't need generics in Go, and I hope people don't force them into their code where an interface would do just fine. I'm a big fan of good type systems like Rust, but Go doesn't need all that power all over the place. I think generics are a good feature for Go, but I really hope they don't get overused in places that would currently use an interface.
I doubt more complex features than this will be added, considering how long it took to get generics.
Rust is a very different language from Go, though it can do similar things. If you have people willing to learn it, you can certainly try, though you might find the ecosystem lacking.
If they will make code harder to read, that's up to syntax. I don't know how all that will look up on the end, but it should be reasonably easy to just write an example.
do you mean templates?
i was under the impression that c++ generics == templates, but after a google search found out that c++ has both (at least according to microsoft), not surprised
https://docs.microsoft.com/en-us/cpp/extensions/generics-and...
It is an extremely niche language, extremely rarely used even in the .NET ecosystem, except sometimes as glue code.
Normal C++, including MSVC C++, has only templates.
This is the kind of tooling that makes me still reach out for C++ when going outside managed languages.
Go is fairly dominant in some areas and Rust is not really a realistic replacement today. Generics will not change that.
Perhaps that will change as you get more used to it?
And for code you consume (e.g. using a library) Generics will make your life easier and safer.
Pretty much any mainstream language that supports generics is shit to read. (And I love to read code.)
You're just getting old is all.
What was once familiar now isn't ... how annoying.
If that worries you, don't: we're all walking down that path.
Give it a couple of decades and everything in your life will feel like that.