19 ms·
A Proposal for Adding Generics to Go
- azhenley 6y agoHow many different proposals for generics have there been?
- nappy-doo 6y agoI think this makes the third official attempt. I have high visibility into the process, and I think it's likely this one will stick. It'll likely take 2 releases (as Ian stated) to get it done.
- EwanToo 6y agoThere's been quite a few early proposals and drafts. This is the first one that I'm aware of that Google have agreed to implement.
- spf13 6y agoThis is the first. There have been several designs previously, each of which was refined based on feedback, culminating in this proposal.
- dgb23 6y agoI have observed it from afar and my impression is that this is a close to final step in a long series of careful iteration, discussion and research.
- throw_m239339 6y agoActually not that much, I remember 2 very different proposals, including this one. The previous one was confusing as F and the antithesis of the simplicity Go claims it abides by. It felt very much like a plot to add generics without ever using the word generics anywhere and looking too much like Java/C#/... The current proposal is basically what you'd expect from generics in a programming language, but a bit more limited. It took basically 10 years, a generation of developers, to quell the opposition against generics in Go, to end up with generics... They might even have unknowingly followed the ADA implementation except that Go's type inference makes them even easier to use. > To use a generic type, you must supply type arguments. This is called instantiation. https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md https://go.googlesource.com/proposal/+/refs/heads/master/des... This is basically how generics as packages in ADA works. I would add that ADA solved many existing problems in Go decades ago... https://en.wikibooks.org/wiki/Ada_Programming/Generics https://en.wikibooks.org/wiki/Ada_Programming/Generics > The generic procedure can be instantiated for all the needed types. Now all Go needs to do is to look at how Ada tasks work in order to fix every single issue with Go routines...
- wejick 6y agoI'm curious what's the issue with go routine and what kind of fix ADA bring?
- boyter 6y agoNot familiar with Ada but the inability to stop running goroutines from outside it is annoying and leads to a lot of state telling them to exit. Sometimes I just want it to stop now.
- wejick 6y agoIt's not like on pthread where we have a trhead handler, that will complicate many things. Like you said, We stop the go routine by telling it to exit the function, it's quite straightforward I think. Not more than a channel and switch case (+ context)
- rbranson 6y agoHow would you expect that to actually work though? If a goroutine could be arbitrarily stopped at any point, that would trivially lead to degenerate program states. A lock could be held open or another goroutine could be waiting on it for a message.
- wejick 6y agoIt's very good to witness the journey of generic, how the team is very cautious and dedicated to bring Go way of perfection. IMO This is something that can't be done by a committee of so called industry players.
- hackyhacky 6y agoAs much as I've cursed the lack of generics and the limited expressiveness of Go's type system, it's hard for me to reconcile these proposals with what I know of Go. Go was conceived as a small language, a successor to C, and purposely eschewed "new-fangled" features of modern languages. Whether the result is good is a matter of taste, but I feel that retroactively bolting on a modern type system will simultaneously (a) undercut the simplicity of the core language and (b) produce a language that is not as clean as those conceived with generics from the beginning.
- dgb23 6y agoOne could argue that parametric polymorphism is a form of simplicity, because it disentangles algorithms from concrete types.
- kitkat_new 6y agoThe lack of generics makes it only more complex. Simplicity: yes, but in a senseful manner. Omitting generics is not senseful to me.
- hackyhacky 6y agoI agree. But if you like generics, why not use a language that already has them, e.g. Rust, Haskell, etc.
- mrnothing_123 6y agomaybe you already use go-lang, and want generics.
- DaiPlusPlus 6y agoAny successor to C needs to be type-safe. Generics make that easier.
- hackyhacky 6y agoWhy? C isn't type-safe.
- kitkat_new 6y agoI hope at some point they manage to add it. I, however, discovered Rust in the meanwhile. It has generics. And it is not too complex either and has quite a few other bonuses.
- skrtskrt 6y agoI like Go, but I too in the meantime have dipped my toes into Rust and it's just so much better without being that much more complex. The learning curve is real but quite a bit overstated I think.
- egeozcan 6y agoThere's this common belief that "rust is too hard", which used to be actually true, but the docs and the language itself came a long way since those times. I'd say: If you can code in C#/TS (or anything like) + go, then it only depends if you have a free weekend.
- dgb23 6y agoRust has quite a few concepts you won't find in (some of) those languages like borrowing, lifetimes, traits, monomorphization, macros, type semantics around concurrency, (partial) expression based syntax, pattern matching and match guards... However you can litter your code with unwrap and clone to reach the finish line quickly, but then you lose the two main value props of the language and likely lose performance and runtime consistency over other languages.
- mikepurvis 6y agoNew concepts, yes, but I think anyone who has spent any significant time programming in C++ will immediately recognize the problems that they are solving and how the solution works. That significantly eases the learning curve in my opinion.
- recursive 6y ago
- jagger27 6y agoHere's the actual proposal: https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md https://go.googlesource.com/proposal/+/refs/heads/master/des...
- cletus 6y agoAnother comment mentions this is the third (serious) attempt at adding generics to Go. Is there any concise history of these attempts (including this one)? I'd like to understand the gist of these proposals and what ultimately derailed them. By themselves these proposals are pretty inscurtable.
- cratermoon 6y agoThe golang nuts mailing list archive might be the best place to start. https://groups.google.com/g/golang-nuts https://groups.google.com/g/golang-nuts
- philosopher1234 6y agoThat is surely a history, but concise? Nope...
- cratermoon 6y agoWhat I meant was, go ask there.
- tomlu 6y agoThe major difference is the first proposal separated interfaces from concepts, later proposals (very wisely) unified them. Only concepts could be used in type constraints. They also switched from parenthesis () to square brackets [], thankfully.
- tschellenbach 6y agoWe have a very large Go codebase here at Stream and not having generics is just not really as big of an issue as you think it is. There are plenty of work arounds if you get used to not having generics in the language. The fast compile times of Go are amazing. I was doing some Kotlin a few weeks ago and the difference is crazy. Go: Install deps, compile everything done in 5s. Doing the same in Kotlin, laptop freezes, android studio freeze, time to get a coffee :) That being said it would be really nice to have some reusable map type structures that handle GC better than the default maps. Fingers crossed.
- egeozcan 6y agoI actually just need generic Sets. Generic map/reduce on slices wouldn't hurt too. OTOH, it's 2021 and look at what we are wishing. My love/hate relationship with golang is like the one I have with Apple.
- jjtheblunt 6y agoisn't generic Sets easily implemented with map being already generic?
- atombender 6y agoOne challenge there is that identity is only supported for some built-in types — only primitives, and structs of primitives; no pointers, slices, maps. If you want a set of some complex kind of value that contains non-map-indexable types like slices and pointers, then you have build an indirection around it. A good set implementation needs to support a comparison operation. I really wish this existed for Go maps, too.
- fileeditview 6y agoYes and that's probably why there is no set in the go std lib. You just can use struct{}{} as (empty) value in a map.
- 6y ago
- jcelerier 6y agoevery language designer who does not understand c++ is doomed to reinvent it I mean, seriously, func F[T any](p T) { ... }
- pkaye 6y agoWhat is wrong with that syntax?
- jcelerier 6y ago? nothing is wrong, it's just a different way to spell template<typename T> void F(T p) { ... }
- moocowtruck 6y agocan i say T : SomeConstraint ?
- jcelerier 6y agoin C++ ? sure template<SomeConstraint T> void F(T p) { ... } or just void F(SomeConstraint auto p) { ... } like this for instance: https://gcc.godbolt.org/z/hPM38T https://gcc.godbolt.org/z/hPM38T
- moocowtruck 6y agocool, can i even add two constraints? or is it limited to one. Oh i see you have include concepts, is that new to c++20 then?
- esarbe 6y agoNo, not acually. Generics in Go are vastly different than templates in C++. They might be used for similar things, but whereas Go's generics actually build up on Go's structural typing, templates are ... something completely different again. I mean; C++ templates are Turing complete. They are in the same ballpark as Scala's type machinery. And I say that with adoration.
- oefrha 6y agoRelated earlier discussions: - https://news.ycombinator.com/item?id=20576845 https://news.ycombinator.com/item?id=20576845 (2019 draft) - https://news.ycombinator.com/item?id=20541079 https://news.ycombinator.com/item?id=20541079 (also 2019 draft) - https://news.ycombinator.com/item?id=23543131 https://news.ycombinator.com/item?id=23543131 (2020 draft, i.e. the base version of the current draft)
- karmakaze 6y agoAlso the video[0] linked in the post seems to be ~Dec 2020 which is new to me. [0] https://www.youtube.com/watch?v=TborQFPY2IM https://www.youtube.com/watch?v=TborQFPY2IM
- cratermoon 6y agoI look forward to generics in Go. Yes, it's possible to do it with reflection, interfaces and interface{}, but it's not typesafe, it's not fast, and it's prone to code bloat. I'm a fairly late-comer to generics, I never programmed seriously in C++, I avoided generics in Java initially, and I wrote a lot of code in less statically-typed languages. Ever since the first serious talk of generics in Go 2.0 I've endeavored to educate myself and I now am very strongly in favor of them.
- moocowtruck 6y agogenerics in go will be a great addition, also it is important to realize generics in java and go are different such that go uses structural typing vs nominal
- cratermoon 6y agoYup, and they are different from generics/templates in C++ as well.
- dgb23 6y agoI find the proposal interesting. Type constraints might help to reason about a given abstraction. If I understand correctly they behave quasi like sum types over interfaces. From skimming here: https://go.googlesource.com/proposal/+/master/design/go2draft-type-parameters.md https://go.googlesource.com/proposal/+/master/design/go2draf... They don't feel like generics in for example Java (my Java is rudimentary), but rather like an abstraction over interfaces. Can anyone elaborate on this?
- candiddevmike 6y agoIt's too bad this is targeting end of year, I have so many applications for this--test assertions, http controllers, SQL--this will remove a lot of duplicate code. I also think it will expand use cases for Go, especially in the UX area where you have to implement duplicative getters and setters.
- rowanseymour 6y agoI rarely find myself frustrated with the lack of generics in Go and am so glad to never deal with the kind of over-engineered generic madness that is so common in Java, except... When dealing with collections. It's maddening to have to keep duplicating basic functions like getting the keys from a map, or checking if a slice contains a given item.
- echelon 6y agoAren't collections 30% - 40% of code? (We seldom deal with just one thing.) That's why I feel generics are so important. You can build complicated messes with any programming paradigm. It's a matter of discipline to use the tool correctly. Don't hate on generics, but rather the unskilled use of them (which I frankly see far less than abuse of other patterns/paradigms/language features). The biggest negative with generics is compile time, but the clarity and conciseness of generics is worth it for me.
- gher-shyu3i 6y ago> and am so glad to never deal with the kind of over-engineered generic madness that is so common in Java Over engineered how?
- wtetzner 6y agoI don't think I've ever seen generics be the cause of over-engineered complexity in Java. It's pretty much always giant, complex class hierarchies or a bunch of reflection (or both).
- Animats 6y agoTwo more levels of blogs down, the actual proposal.[1] Definition: // Print has a type parameter T and has a single (non-type) // parameter s which is a slice of that type parameter. func Print[T any](s []T) { ... } Call: Print[int]([]int{1, 2, 3}) Above, "any" is really just a synonym for "interface{}". You can have more restrictive type constraints on parameterized types by specifying other Go interfaces. This is vaguely similar to how Rust does it, and quite different from the C++ approach. "This design does not support template metaprogramming or any other form of compile time programming." [1] https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md https://go.googlesource.com/proposal/+/refs/heads/master/des...
- fanf2 6y agoMy understanding from the “Featherweight Go” paper https://arxiv.org/abs/2005.11710 https://arxiv.org/abs/2005.11710 is that generic types will not simply be a synonym for interface{} because the compiler will be able to monomorphize them - they do not require dynamic dispatch like interfaces.
- oconnor663 6y agoI think the comment above meant that the `any` keyword specifically is a synonym for `interface{}`, not that all generic types will be.
- mseepgood 6y ago> My understanding from the “Featherweight Go” paper https://arxiv.org/abs/2005.11710 https://arxiv.org/abs/2005.11710 is that generic types will not simply be a synonym for interface{} The `any` constraint is a synonym for the `interface{}` constraint.
- lights0123 6y ago(also C++ concepts)
- anderspitman 6y agoI've been heavy into Go the past year. I love the simple interfaces they've built over some rather complicated things (concurrency, cross-compilation, networking, etc), which really do tend to just work. I fear that Go will eventually turn into something where we look back and realize we've lost something important by gaining a lot of less importants. The impulse to change things is just too strong these days. C89 has done just fine unchanged for 30 years. All I want is a C+=1 I can rely on for the next 30 years.
- nine_k 6y agoWith all the CVEs we see every month due to what can be only called design flaws in C, I have a hard time saying that C did fine for last 30 years. For C+=1, I'd look at Zig; it unfortunately lacks the excellent corporate support that Go enjoys. To me, Go looks much like early Java, only with a much better concurrency and saner "OOP". If anything, generics made Java better in many ways, without sacrificing performance or usability. It took 7 years for Java; it's going to take closer to 10 years for Go, bur better late than never.
- bcrosby95 6y agoI think they're talking about the simplicity of C. But yeah, I like to think of Go as a Java for the new millennium. We're a Java shop and lots of people hate some of the newer changes to the language. And how OOP focused it is. I think Go would be a better fit because it seems to match the philosophy of our team more. But don't really think it's worth the switch for us.
- anderspitman 6y agoI've used Java and Go. I find Go a far superior experience. Part of that is the standard library which seems to strike a perfect balance providing what you need but not too much. I also think a lot of it has to do with the culture of the languages. Kotlin is a pretty nice language, but using it for Android still makes me want to hit my computer with a hammer because the over-abstraction of the Java ecosystem is maddening.
- ed25519FUUU 6y agoI'm really mixed about this. As a developer I would love having generics in Go. I can think of a few places in my code I can greatly simplify if they were implemented now. However, as someone who reads other people's Go code, I'm not a huge fan. One of the greatest things about Go is that a developer can usually one-shot read and understand almost anybody's code because there's a simplicity "forcing-function" applied to everything. To lose that would be a shame.
- __jem 6y agoIn other words, go is the language you want your coworkers to write, not the language you want to write. :)
- ed25519FUUU 6y agoI agree totally with this sentiment. I love reading other people's Go code but not always writing it, which is basically the opposite of virtually every other programming language I've used.
- erik_seaberg 6y agoI’m reminded of “languages designed for the masses”: https://news.ycombinator.com/item?id=899246 https://news.ycombinator.com/item?id=899246
- whateveracct 6y agoparametric polymorphism does not make code harder to read you know what's hard to read? hand-rolled for loops & select blocks combined to wrangle concurrency. the no1 benefit of parametric polymorphism in Go is going to be abstracting over concurrency
- JamesSwift 6y agoExactly. I found myself so frustrated when learning Go and digging into the "gotchas" of goroutines. There is so much non-obvious complexity that could be completely avoided by providing generics so that someone else can develop a package to handle the issues for you.
- systemvoltage 6y agoSide tracking a bit: I wish there was a popular programming language like Go with rust-like package manager, Python style syntax and ability to hack, compilable, classic (classes, methods), and fast. Or I wish Go had classic OOP and raise Exception methods. Basically, I want fast statically typed python with better package management. Or other way to put it, I want Go with classic OOP and Exceptions.
- switch007 6y agoThis, kinda! But I'm after: - Python's OOP, stdlib, exceptions - Go's fast compilation and binaries - Rust's package manager (never used but I heard it's amazing) - Java's third-party packages & tooling - F#'s expressiveness, FP, type system (never used it, only read a few intro articles, but it looks very nice?) I'm tyring to move on from Python but finding it difficult to decide what to learn next.
- Varriount 6y agoYou might be interested in Nim (https://nim-lang.org https://nim-lang.org). I can't say that it's very object oriented, but it is very flexible.
- systemvoltage 6y agoThat's awesome, I will check it out. Just looking at initial syntax, you just made my day!
- djhaskin987 6y agoWould someone mind enlightening me as to what the difference is between this draft and the 2020 draft.
- ianlancetaylor 6y agoVery little. The announcement here is not a new draft, it is starting the formal proposal process for adding type parameters to the language.
- msie 6y ago"If the proposal is accepted, our goal will be to have a complete, though perhaps not fully optimized, implementation for people to try by the end of the year, perhaps as part of the Go 1.18 betas."
- betimsl 6y ago> Interface types used as type constraints can have a list of predeclared types; only type arguments that match one of those types satisfy the constraint. Wait... But why?gif
- eplanit 6y agoI wonder how long it will take for Go to become like Java by adding baggage like this. As soon as you see Enterprise Go, it's over.
- alkonaut 6y agoFinally. Hope it gets approved. It's strange that they don't consider Print[T](x T) instead of Print[T any](t T). The "any" could just be omitted without loss of anything. Especially since repeated types with the same constraints indeed DO omit it! Print2[T1, T2 any]
- setr 6y agowell, it doesn't omit it; it just applies it to all preceding arguments that didn't have a qualifier, same as normal golang function arguments. It's still being explicit about the constraint being `any`
- uluyol 6y agoThe any is required to avoid a syntactic ambiguity. It was that or use the "type" keyword as in Print[type T] / Print[type T1, T2 Constraint]. The question of what the syntax should look like has been beaten to death.
- alkonaut 6y agoThere is ambiguity in Print[T](t T)? What different things could T represent there?
- ianlancetaylor 6y agoThere is no ambiguity there. The ambiguity arises for parameterized types. type A[T] int Is that a parameterized type named A with a type parameter T, or is it a definition of an array named A whose length is T? Separately, it's nice that type parameter lists use the same syntax as non-type parameter lists.
- majewsky 6y agoI'm incredibly interested† to see how this is going to affect kubernetes/client-go and friends. † Deliberate use of a neutral adjective.
- wrnr 6y agoSometimes I miss java stream API in Go, maybe this can be a first step to implementing a similar lazy functional programming interface.
- the_arun 6y agoSlowly Go will become Java :) Go -> Guava -> Java
- _QCanaria_ 6y agoThe carefulness of the Go team when introducing new features is remarkable. After many years chasing the newest, shiniest and best tools I can't appreciate stability and a large and useful standard lib enough. I finally understood the importance of the boring stack. I don't need generics in Go, but I'm happy they are coming. Especially for collection methods.
- smokey_circles 6y agoGenerics are awful. They solve no problem in the domain space, only the developer space. Which then creates the problem of developers who insist on writing infinitely extensible generics with indecipherable bounds. Just repeat code. You'll be fine. If you find yourself repeating a LOT of code because Go does not support generics, maybe stop and think about your design. Putting generics in as an escape hatch will do you more than good, guaranteed