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.

Operator constraints in Go

47 pointsby Meroviusalmost 3 years ago

6 comments

lalaithionalmost 3 years ago
For a function, it makes sense to just write two functions, the easiest to use, and the one with maximum flaxibility.<p><pre><code> func SortOrdered[T constraints.Ordered](s []T) { &#x2F;&#x2F; … } func Sort[T any](s []T, less func(T, T) bool) { &#x2F;&#x2F; … } </code></pre> For a data structure, I recommend using<p><pre><code> type SearchTree[T any] struct { Less func(T, T) bool &#x2F;&#x2F; … } </code></pre> and then writing two constructors<p><pre><code> func NewSearchTree(less func(T, T) bool) *SearchTree[T] { &#x2F;&#x2F; … return &amp;SearchTree[T]{ Less: less, &#x2F;&#x2F; … } } func NewOrderedSearchTree[T constraints.Ordered]() *SearchTree[T] { &#x2F;&#x2F; … return &amp;SearchTree[T]{ Less: func(x, y T) bool {return x &lt; y}, &#x2F;&#x2F; … } }</code></pre>
评论 #31484347 未加载
jeffbeealmost 3 years ago
Hrmm. How do float32 and float64 satisfy constraints.Ordered? The Go spec (which is almost uselessly vague and will some day contain 1000 pages of caveats) just says that floats are &quot;comparable and ordered, as defined by the IEEE-754 standard&quot; but of course that standard doesn&#x27;t really say that, it specifically says that NaN are unordered. I just checked quickly with Compiler Explorer and float32&lt;float32 emits UCOMISS on x86, which makes sense, resulting in 42.0&lt;NaN and NaN&lt;42.0 both being false, as expected. So how does it handle the constraint for float?
评论 #31483846 未加载
评论 #31483875 未加载
karmakazealmost 3 years ago
Nice write-up and summary. The emoji chart would be easier to visually parse with more traditional symbols e.g. [I realize these Unicode symbols could also be considered emoji but are less emotional.]
评论 #31490721 未加载
avgcorrectionalmost 3 years ago
I don&#x27;t program in Go. But I could imagine that I might at some point want to sort a list of a custom struct by one of its members. And that&#x27;s probably as advanced as it would get for my purposes.
评论 #31483960 未加载
TheDesolate0almost 3 years ago
Imagine looking at a Garbage Collected language that isn&#x27;t even a complete language (You just got generics, FFS) and thinking, &quot;Yeah, this is a great idea!&quot;
gavinrayalmost 3 years ago
What is shown in the examples I know as the term &quot;generic interface&quot; or, in some fancy languages, &quot;typeclasses&quot;