TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Trying Out Generics in Go

215 点作者 bullcitydev超过 3 年前

17 条评论

jamespwilliams超过 3 年前
One annoying bit about Go&#x27;s generics is that you can use type parameters in functions, but not in methods.<p>So for example, maybe you&#x27;d want to write a Map function for the Optional type in this article, which returns None if the option is None, or calls a given function with the value of the Optional otherwise.<p>You&#x27;d probably write it like this:<p><pre><code> func (o Option[T]) Map[U any](f func(a T) U) Option[U] { ... } </code></pre> But that doesn&#x27;t work: &quot;option&#x2F;option.go:73:25: methods cannot have type parameters&quot;<p>The type inference is also a bit limited, e.g: let&#x27;s say you have a None method:<p><pre><code> func None[T any]() Option[T] { ... } </code></pre> And you call it somewhere like:<p><pre><code> func someFunction() option.Option[int] { if (!xyz) { return option.None() } &#x2F;&#x2F; ... } </code></pre> it isn&#x27;t able to infer the type, so you have to instead (in this case) write option.None[int]().<p>Generics is a super cool addition anyway though.<p>Edit: I just found <a href="https:&#x2F;&#x2F;go.googlesource.com&#x2F;proposal&#x2F;+&#x2F;refs&#x2F;heads&#x2F;master&#x2F;design&#x2F;43651-type-parameters.md#No-parameterized-methods" rel="nofollow">https:&#x2F;&#x2F;go.googlesource.com&#x2F;proposal&#x2F;+&#x2F;refs&#x2F;heads&#x2F;master&#x2F;des...</a> which has some details on why method type parameters aren&#x27;t possible.
评论 #29586456 未加载
评论 #29586082 未加载
评论 #29582916 未加载
评论 #29593254 未加载
评论 #29582224 未加载
jaytaylor超过 3 年前
Honest question:<p>Do you think Generics will be an overall win for the Go language, or will they be overused &#x2F; end up making code harder to read &#x2F; harder reason about?<p>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&#x27;m saying this with sadness, as someone who fell in love with Go back in 2012 and still writes it at least weekly.<p>Is it a better bet to move on and go full Rust, rather than bother with wherever the goggle golang train is headed?<p>p.s. Even though code generation is [also] annoying and perhaps not ideal, I&#x27;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.p.s. Generics in other languages like Java or Scala seem fine, as they are &quot;kitchen sink&quot;-style &quot;all things to all people&quot; languages. Such behemoths are nearly always clunkier and less easy to read than pre-generics Golang.
评论 #29582609 未加载
评论 #29582611 未加载
评论 #29584564 未加载
评论 #29582987 未加载
评论 #29582884 未加载
评论 #29582363 未加载
评论 #29582378 未加载
评论 #29583797 未加载
评论 #29582546 未加载
评论 #29582605 未加载
评论 #29584524 未加载
评论 #29582431 未加载
评论 #29582614 未加载
评论 #29585159 未加载
评论 #29593399 未加载
评论 #29584064 未加载
评论 #29585474 未加载
评论 #29582852 未加载
评论 #29582215 未加载
评论 #29585435 未加载
评论 #29582229 未加载
评论 #29589241 未加载
评论 #29586140 未加载
评论 #29582565 未加载
评论 #29583900 未加载
coldtea超过 3 年前
&gt;<i>My first response when the plan to add generics was announced was “meh”. 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><p>And then the author goes to admit that they had written a whole library with the kludge that is textual code generation &quot;to support both primitive and custom types&quot;.
评论 #29589319 未加载
dmnd超过 3 年前
Amusing that this post goes from<p>&gt; My first response when the plan to add generics was announced was “meh”. 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. Most of the code I write in my day job is very specific to the domain and doesn’t fit the use case that generics aim to fill.<p>to<p>&gt; I love that I was able to delete 95% of my code because of generics.
评论 #29591420 未加载
评论 #29589441 未加载
hmmdar超过 3 年前
Another way to do `Option` without pointers could be similar to the following with a struct with two members.<p><pre><code> type Option[T any] struct { v T isSet bool } func NewOption[T any](v T) Option[T] { return Option[T]{ v: v, isSet: true, } } func (o Option[T]) Get() (v T) { if !o.isSet { return v } return o.v } func (o Option[T]) IsSet() bool { return o.isSet } </code></pre> With this pattern you&#x27;re able to use `Option` as a value without pointers.<p><pre><code> var o Option[int32] o = NewOption(int32(1)) fmt.Println(&quot;value:&quot;, o.Get()) fmt.Println(&quot;is set:&quot;, o.IsSet()) </code></pre> Alternative separate `Get` and `IsSet` methods, is to combine them into one, similar to map look up pattern.<p><pre><code> func (o Option[T]) Get() (v T, isSet bool) { if !o.isSet { return v, false } return o.v, true } var o Options[int32] v, ok := o.Get() &#x2F;&#x2F; zero, false o = NewOption(int32(1)) v, ok = o.Get() &#x2F;&#x2F; 1, true</code></pre>
评论 #29584065 未加载
评论 #29583991 未加载
Smaug123超过 3 年前
I think you&#x27;re making it easy on yourself by choosing &quot;a library whose sole purpose is to stamp out the boilerplate needed to work around Go&#x27;s lack of generic algebraic data types&quot; to demonstrate how good generics are :P
评论 #29581889 未加载
unix1超过 3 年前
I too was playing around with Go generics. I wrote some naive concurrent filter and fold (reduce) functions for slices and maps here <a href="https:&#x2F;&#x2F;github.com&#x2F;unix1&#x2F;gostdx" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;unix1&#x2F;gostdx</a> if anyone is curious how those would feel.
bullcitydev超过 3 年前
Author here. I just removed the previous section I had around using build tags because I realized I was using `&#x2F;&#x2F; +build 1.18` instead of the correct `&#x2F;&#x2F; +build go1.18`. Oops.
评论 #29581867 未加载
评论 #29581662 未加载
amelius超过 3 年前
Side question: Are there any languages that transpile to Go?
评论 #29587137 未加载
Laremere超过 3 年前
My opinion with 9+ years since first learning Go, multiple of those using it for a full time job:<p>Putting the end first, my rule of thumb for using generics in Go is: Don&#x27;t go down the OOP road of over planning and programming with fancy type work. 99% of the time, the common Go programmer won&#x27;t need to write any generics. Instead, just focus on actually solving the problem and manipulating the data like you would normally. If you encounter a place where code is repeated and complicated enough to be worth a new function, move it to one. If you find yourself repeating multiple functions but with different data types, turn that into one generic function.<p>Generics are an incredibly useful addition to the language that I&#x27;ll almost never use. Really to be more precise, Go has had some generics this whole time: Maps, slices, arrays, and channels all have type parameters, and have covered the vast majority of my needs. There are a few times where I&#x27;ve wanted more general generics, though:<p>- The sort and heap packages are rough to use. You need to specify a bunch of nearly identical functions just to get them to work on any custom type. The generic versions (not coming in 1.8&#x27;s standard library, iirc) will be much easier to use.<p>- Was writing an Entity-Component-System game for fun, and needed a weird custom container. Turned to code generation, and really that turned out to be necessary anyways because it did more than any (non-metaprogramming) generics could do.<p>- We had one very complicated multiple Go routine concurrent data structure that needed to be used for exactly 2 different types. Others were writing the code, and very afraid of using interface{}. This is despite there only being a handful of casts. In reality if they caused a bug, it would be found immediately. There&#x27;s a strong hesitation around type safety dogma that isn&#x27;t risky in practice. Still, generics would&#x27;ve been the preference here.<p>- I was parsing WASM files, and there&#x27;s a common pattern for arrays where it encodes the length of the array, then that many objects in a row. It led to a lot of minor code repetition. Replacing that with a generic function that took a function to parse a single object, and returned the array of those objects was a nice, but relatively minor win.<p>On the other hand:<p>I&#x27;ve never really been bothered by having to do sets like map[int]struct{}. There was one case where I saw someone put set operations out into a different library. I eventually found to my dismay that the combination of how the set library was used, and how it was implemented caused a performance critical part of the code to be several orders of magnitude slower than it needed to be. Had this code been more idiomatically inlined, this flaw would have been more immediately obvious.<p>I really don&#x27;t like seeing map&#x2F;reduce&#x2F;filter type functional programming coming into Go usage. This type of code tends to need more dramatic changes due to minor conceptual changes, more than direct procedural code does. Also like the set example, how you iterate and manipulate objects can have large performance implications that using such functions hides away.
dsnr超过 3 年前
That’s a welcome feature even though I don’t like the syntax. But Go could become the perfect language if they just fixed error handling and a couple small annoying quirks.
评论 #29582173 未加载
评论 #29582148 未加载
评论 #29582369 未加载
评论 #29582240 未加载
fnord77超过 3 年前
I see they went with []. Scala does this and it annoys me because [] also denotes arrays. Unlike &lt;&gt; which doesn&#x27;t have any overloaded meaning.
评论 #29585812 未加载
geoka9超过 3 年前
It could be my personal negative experience with maintaining code that overuses generics in other languages, but I have reservations about this feature. I almost never need them, but on the other hand I don&#x27;t feel too good about having to repeat myself when writing library packages.<p>I almost feel I would be happy with generics in Go if Go made them illegal in anything but libraries (not allowed in package main, maybe? Or not allowed in a package unless it gets imported by another package?).
评论 #29584748 未加载
bruce343434超过 3 年前
How does Go handle the ambiguity between [] meaning generics and [] also meaning array?
评论 #29582889 未加载
评论 #29583583 未加载
xyst超过 3 年前
person deleted 95% of code, but what about performance? is it more or less the same as the non-generic implementation?
评论 #29585339 未加载
random314超过 3 年前
This is a phenomenal achievement, that I didn&#x27;t expect to see in my lifetime!<p>Gives me hope that P vs NP will be resolved in my lifetime too!!
评论 #29600671 未加载
FpUser超过 3 年前
&gt;&quot;In case you’ve been living under a rock ...&quot;<p>Not really but getting to know Go is not on the list of my priorities.<p>Looked at examples. Many languages use angle brackets for generics and templates but in case of Go they had to do it their own way and use square brackets that most programmers would perceive as an array. Funny.
评论 #29587643 未加载
评论 #29593464 未加载