TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Why Generics?

218 pointsby johnvegaalmost 6 years ago

28 comments

iainmerrickalmost 6 years ago
Maybe this is unfair, but it’d be great if the Go devs could just say “generics will work similarly to [C# &#x2F; Java &#x2F; Swift &#x2F; D &#x2F; whatever], except that we’ll address [problems] with [adjustments]”.<p>Rather than going through this whole rigmarole of resisting adding generics too early because all existing implementations are bad, then slowly reinventing the wheel from scratch, then finally ending up with something pretty similar to one of those other languages anyway.<p>It’s OK not to make something completely new and different. It’d be useful to explicitly say which language(s) you’re borrowing from because you can then more clearly call out the differences and explain the reasons for them.
评论 #20578392 未加载
评论 #20578502 未加载
评论 #20578172 未加载
评论 #20583183 未加载
评论 #20579970 未加载
评论 #20583336 未加载
评论 #20578915 未加载
jsgoalmost 6 years ago
Generics with Reflection was the first gut check I experienced while working after completing college and getting an ASP.NET job. Like 2-3 weeks into said job.<p>Had to do an application that dealt with 4-5 forms (can&#x27;t remember). Like 300 fields on the bigger ones, smaller ones 50ish. I started out on one that was mid-200. I&#x27;m coding the way I was taught in school: object set object properties based on txtWhatever.Text. Like 240ish times. I can&#x27;t remember how many lines of code were in this code behind, but it was substantial.<p>I turn it in, it works. Go me, let me go on to the next one. The senior guy on the team does one of the smaller forms. But he uses generics and reflection to basically iterate over all of the fields on the form and sets them to the ephemeral properties on this generic object in like 8-9 lines of code. Then there was the rendering code that was vaguely similar.<p>Added bonus: 99% of his code behind could be copy and pasted over to the newer forms and handle all of the work related to getting&#x2F;setting form values. After the code proved to work for a few weeks, replaced the massive code behind with call to his code (passing in the form object and the generic to be set and used later) with the same result and one area to manage code and it isn&#x27;t an insanely large code behind file (got better with not one filing everything in time too).<p>Not saying generics and&#x2F;or reflection are a silver bullet (I don&#x27;t feel they are. Rarely so do they end up being the thing I go for), but it was definitely eye opening that straying from &quot;see spot run&quot; code could be advantageous. And that I wasn&#x27;t &quot;good to go&quot; already.
elpakalalmost 6 years ago
Chiming in here as a Swift dev - I find its generics system incredibly helpful and end up writing something that uses generics about once a month. To those Go programmers who think they will never use them - it’s worth a little learning, and once you do you will find more ways to use them to make your code more applicable.
评论 #20577795 未加载
评论 #20577840 未加载
jknoepfleralmost 6 years ago
The decision to overload parentheses to express generic type is the only part of this spec I find nauseating. It doesn&#x27;t scan well, and doesn&#x27;t have a precedent in any major generic implementation I&#x27;m aware of. &lt;, [, @-annotation... I don&#x27;t care. Just don&#x27;t mush it into the function declaration with the same syntax that encloses parameter.
评论 #20578260 未加载
评论 #20579433 未加载
parhamnalmost 6 years ago
That time of week to rehash all the Go Generics comments!<p><a href="https:&#x2F;&#x2F;hn.algolia.com&#x2F;?query=generics&amp;sort=byPopularity&amp;prefix&amp;page=0&amp;dateRange=all&amp;type=story" rel="nofollow">https:&#x2F;&#x2F;hn.algolia.com&#x2F;?query=generics&amp;sort=byPopularity&amp;pre...</a>
评论 #20580605 未加载
moominalmost 6 years ago
<p><pre><code> Go 3: Why HKT? Go 4: Why homoiconicity? Go 5: Why uniqueness and borrowing?</code></pre>
评论 #20577293 未加载
评论 #20577524 未加载
评论 #20583941 未加载
haolezalmost 6 years ago
Personally, I prefer the current interfaces-based solution to generics. It&#x27;s a little verbose, but keeps the language simple.<p>However, I think that the people we should be listening most are the ones developing huge projects in Go, like Kubernetes. Would having generics with this new contracts thing make it easier to develop and maintain e.g. Kubernetes? I&#x27;m truly curious.
评论 #20577651 未加载
评论 #20577571 未加载
评论 #20577552 未加载
评论 #20580534 未加载
评论 #20582308 未加载
评论 #20577806 未加载
评论 #20577521 未加载
评论 #20577484 未加载
twodavealmost 6 years ago
Generics and interfaces go hand in hand IMO, especially in an application with heavy emphasis on data persistence. This way you can compose a class of some interfaces, pass it to a persistence layer (using a generic constraint of something common to all inputs of that layer), and then the persistence layer can check for all the interface types it cares about saving and pass those pieces off to whatever lower-level piece of code handles that one thing.<p>Generics enable you to avoid having 10 slightly different implementations of the same thing (even if dependencies are shared, you&#x27;re still going to have 10 copies of plumbing without generics). Being wise about when and when NOT to use generics is to me the most important factor.<p>In our shop we tend to not introduce a new generic class&#x2F;method until something gets painful (unless it&#x27;s plainly obvious from the beginning). Because of this we usually begin to notice and reason about patterns in our code that seem common enough to warrant refactoring and whether the complexity of a generic implementation would be worth lowering the maintenance burden of copy&#x2F;pasting said pattern all over the place. It&#x27;s a case by case decision.<p>Having generics available at least allows us to make that decision for ourselves.
wrsalmost 6 years ago
The examples I’d like to see worked out fully, which he mentions in passing, are encapsulation of concurrency patterns (parallelization, work queues, cancelling, etc.). It’s not that big a deal to write Max as a function or even inline, whereas there are serious practical pitfalls and common mistakes when doing real work with channels. It would be a lot more effective to fix these by writing library code rather than writing Gophercon presentations.
Filligreealmost 6 years ago
Why generics, indeed?<p>There must be an answer to this, but I&#x27;ve never seen a good response to why they aren&#x27;t implementing parametric types and (single-parameter) typeclasses instead.<p>Simplicity? Yes, but generics are hardly any simpler.
评论 #20577842 未加载
评论 #20577779 未加载
mitchellhalmost 6 years ago
It might be fun to share my viewpoint from an angle that&#x27;s probably fairly unique.<p>I&#x27;ve started a number of large, highly deployed Go projects: Terraform, Vault, Packer, Consul, Nomad, and numerous libraries and other things. I started a company that employs hundreds of full time Go developers. Go has been one of our primary languages since Go 1.0 (and I used it prior to that).<p>Let me start by saying that there are _definitely_ cases where generics are the right answer. Usually when I talk about generics people tend to assume I disagree with the whole concept of generics but I certainly do not. Generics are useful and solve real problems.<p>Adding this paragraph after I already wrote the rest: this whole comment ended up sounding super negative. I&#x27;m voicing concerns! But, I think that the design proposal is exciting and I am interested to see where it goes. There are definitely places generics would be helpful to us, so please don&#x27;t take my negativity too strongly.<p>## Technical Impact<p>Having written these numerous large, complex systems, I believe there are less than 10 instances where generics would&#x27;ve been super helpful. There are hundreds of more times where it would&#x27;ve been kind of nice but probably didn&#x27;t justify the complexity of implementation or understanding.<p>This latter part is what worries me. I&#x27;ve worked in environments that use a language with generics as a primary language. It&#x27;s very easy to have an N=2 or N=3 case and jump to generics as the right way to abstract that duplication. In reality, the right answer here is probably to just copy and paste the code because the knowledge complexity of using generics (for both producer and consumer) doesn&#x27;t justify it, in my opinion.<p>As a technical leader, I&#x27;m not sure how to wrestle with this. Its easy today because generics just don&#x27;t exist so you have to find a way around it. But for a 150+-sized org of Go developers, how do we have guidelines around when to use generics? I don&#x27;t know yet. I guess that bleeds into human impact so...<p>## Human Impact!<p>Something that is AMAZING about Go today is that you can hire a junior developer with no experience with Go nor any job history, have them read a few resources (Tour of Go, Go Spec, Effective Go), and have them committing meaningful changes to a Go project within a week.<p>I don&#x27;t say this as a hypothetical, this has happened numerous times in practice at our company. We don&#x27;t force or push any new hires to do this, but Go is so approachable that it just happens.<p>I love it! It&#x27;s so cool to see the satisfaction of a new engineer making a change so quickly. I&#x27;ve been told its been really helpful for self-confidence and feeling like a valuable member of a team quickly.<p>The Go contract design document is about 1&#x2F;3rd the word count of the entire Go language spec. It isn&#x27;t a simple document to understand. I had to re-read a few sections to understand what was going on, and I&#x27;ve used languages with generics in a job-setting and have also been a &quot;professional&quot; Go dev for 9 years.<p>So what worries me about this is technical merits aside, what impact does this have on learning the language and making an impact on existing codebases quickly?<p>I really like what Ian said about attempting to put the burden of complexity on the _author_ using generics, and not the _consumer_ calling that function. I think that&#x27;s an important design goal. I&#x27;m interested to see how that works out but I&#x27;m a bit pessimistic about it.<p>---<p>I have other viewpoints on generics but those are the two primary ones that stand out to me when I think about this proposal going forward.
评论 #20580064 未加载
评论 #20579344 未加载
评论 #20579398 未加载
评论 #20579099 未加载
aczerepinskialmost 6 years ago
Mixed feelings about this. One of my favorite things about Go is that it&#x27;s a small and relatively simple language. It&#x27;s a &quot;fast enough&quot; language without the steep learning curve of Rust. Too many features that make sense individually could change the calculus to &quot;might as well use Rust&quot;.
评论 #20578519 未加载
fabiensanglardalmost 6 years ago
I hope this doesn&#x27;t happen. I love golang because it is simple and easy to read. Both will go away when generic programmer start to write unreadable meta-programming class which &quot;you don&#x27;t need to understand, just use them&quot;.<p>I admire golang devs for being opinionated and stand up for the core lines of their language so far.<p>I see generic as renouncing these principles.
评论 #20578159 未加载
评论 #20578448 未加载
评论 #20578948 未加载
评论 #20579147 未加载
评论 #20577978 未加载
Pxtlalmost 6 years ago
Go has generics. What it actually lacks is user-defined generics.<p>Which shows the absurdity of the situation. The fact that it has generics demonstrates that generics are a useful and important feature. And yet they think their provided generics cover every possible use-case of generics that you will reasonably need in to use in Go.
评论 #20578069 未加载
zevebalmost 6 years ago
Not certain I like that this is now valid Go:<p><pre><code> func Foo (type T) (t T) (t T, err error) { … } </code></pre> Seems like an awful lot of parentheses in a single line!<p>It&#x27;s a bit tricky to read, because &#x27;generic function&#x27; here means something subtly different from what &#x27;generic function&#x27; means in CLOS …
评论 #20579914 未加载
merlincoreyalmost 6 years ago
As a functional leaning programmer, I think it&#x27;s striking that the resulting draft is essentially a curried function whose first parameter is the type!<p><pre><code> func Reverse (type Element) (s []Element) { first := 0 last := len(s) - 1 for first &lt; last { s[first], s[last] = s[last], s[first] first++ last-- } } </code></pre> This is later called like:<p><pre><code> Reverse(int)(s) </code></pre> Which if this were a curried function, would also be callable like:<p><pre><code> Reverse(int, s) </code></pre> Now I wonder if facilities for currying functions might be a higher level addition that could result in the same thing (so long sa we can pass bare types, which is part of this change as well).
评论 #20580073 未加载
babyalmost 6 years ago
I have two comments to make about this proposaL:<p>1. The type should indicate a generic, not a new syntax. This is better because it is easier to parse for the human eye. For example:<p><pre><code> func Reverse(first _T, second _T) </code></pre> 2. Since all of what generics are is a compile-time code generator, I suggest that Golang forces developers to explicitly list what types are using the generic:<p><pre><code> generics(Add) = {int, string, car, food} func Add(first _T, second _T) </code></pre> This list can be added to, after importing the package:<p><pre><code> Import “thing” generics(thing.Add) += {stuff} </code></pre> This makes code very explicit about its generic functions. It also allow readers to understand exactly where the function is used.
jayd16almost 6 years ago
If I&#x27;m understanding correctly, contracts are a way to implement compile time duck typing? If that&#x27;s the case I think its a pretty neat twist on generics.
SomaticPiratealmost 6 years ago
One of the things I like most about this is that Ian includes the simple mistake in the first function. It’s a bit humbling and acknowledges the fact that even the best of us often make trivial mistakes. It also helps make the point that even the simplest code needs a basic test and adds another argument in favor of generics on the premise of duplicating tests.
wwarneralmost 6 years ago
I feel pretty good reading this. I like that you can write listMyType := List(MyType). I&#x27;m still a bit dubious about contracts; they&#x27;re so similar to interfaces. If there was a way to derive or relate a contract to an interface that would help me.
sp527almost 6 years ago
This process took way too long. I&#x27;ve already moved back to Python3 and am super happy with it. The truth is most software doesn&#x27;t really need the performance benefit Golang offers and you can code up something in Python in at least half to a third of the time it would take in Golang. Aside from agility, there&#x27;s one other benefit that imo matters a lot: reduced LoC. If there&#x27;s one thing I&#x27;ve learned in my career, it&#x27;s that you can never really have too few lines of code, provided it achieves the same result as a hypothetical more verbose alternative.<p>I will admit though that I miss Go&#x27;s CSP implementation and error-handling convention. Maybe I&#x27;ll come back to it in the future after they add generics and fix the dependency system.
评论 #20580104 未加载
clamprechtalmost 6 years ago
Such a succinct article. I wish journalists could explain things this well.
sansnommealmost 6 years ago
I think another area of Go that could use improvements is a more portable standard library optimised for embedded and OS dev. A lot of people want to use Go as a &quot;systems language&quot; and do drivers etc. in it. But the standard library don&#x27;t have good support for freestanding, or at least it&#x27;s not a priority. C and Rust and other languages designed for usage in a non-hosted environment have very clear delineated areas of runtime that requires assembly, manual interfaces for IO&#x2F;memory allocation etc. Go&#x27;s runtime by default assumes the presence of an operating system.
评论 #20577801 未加载
jordiburgosalmost 6 years ago
This looks as an strategy to keep people (and HN) talking about Go.
mleventalalmost 6 years ago
why are people obsessed with simplicity? there&#x27;s a quotation my Einstein that I like to keep in mind: &quot;make things as simple as they can be but no simpler&quot;. the implication being that if you make things too simple then you actually break things. lack of generics makes for software that&#x27;s actually more complex than it needs to be. Take for example Swift: lots of complex features (protocols, all manner of functional transformations, generics, enums, structs, iterators, objects with many method qualifiers, etc) but really nice and efficient to program in.
评论 #20577297 未加载
评论 #20578592 未加载
评论 #20577578 未加载
mcguirealmost 6 years ago
&quot;<i>This article is about what it would mean to add generics to Go, and why I think we should do it. I&#x27;ll also touch on an update to a possible design for adding generics to Go....</i>&quot;<p>This is a situation where <i>who</i> is making the proposal is more important than the proposal.<p>&quot;<i>By Ian Lance Taylor</i>&quot;<p>Oh. Ok. I guess it&#x27;s worth reading then...
013aalmost 6 years ago
The proposed syntax feels like a caricature to me. That something like this could be easily possible:<p><pre><code> func (c Connection) Read(type T Writeable)(into *T) (int, error) { </code></pre> This is quite securely inside shark-jumping territory.<p>Also; I haven&#x27;t seen Rob Pike&#x27;s name really anywhere in these blog posts or discussions, or on any recent Go blog entry. Is he still involved with the Go project day-to-day? I always got the impression that he was one of the bigger anti-generics voices on the team internally.
评论 #20578319 未加载
phlakatonalmost 6 years ago
I do not think generics should be added to Go. It does minimalism and it does it tolerably well. Yet I enjoy using generics in other programming languages. If I had my druthers I&#x27;d be in Haskell-land in more than my spare time.<p>Hence, my modest proposal: Add generics, but make it a brand-new programming language with a totally different name.<p>Sadly, the name Blub is already taken. I propose we call it Glop. Or perhaps: Gong.