Generics: Self Referencing Constraint Types

118 views
Skip to first unread message

jfcg...@gmail.com

unread,
Apr 7, 2022, 4:06:54 AM4/7/22
to golang-nuts
Hi, please take a look.

The aim is to write a HaveLess constraint that will work with any type like Large, without any reflection / traditional interfaces / dictionaries etc., just plain method calls.

How would you write this? Keep in mind that type Large is large :)

Axel Wagner

unread,
Apr 7, 2022, 8:41:31 AM4/7/22
to jfcg...@gmail.com, golang-nuts
At its core, this is this restriction of the current generics design:
That is, there is no real "nice" way to do it.

If you are willing to require a pointer receiver, you can do constraint type inference:
https://go.dev/play/p/L2NiAAM8qE4
Alternatively, it might be appropriate to do away with methods and pass a comparison function:
This has the advantage of being able to use types which you don't control as well.


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/e79c4f92-4508-4ecd-ab32-c47b2d679f78n%40googlegroups.com.

jfcg...@gmail.com

unread,
Apr 7, 2022, 9:21:56 AM4/7/22
to golang-nuts
If you are willing to require a pointer receiver, you can do constraint type inference:
https://go.dev/play/p/L2NiAAM8qE4

A single cast worked nicely, thank you.
Reply all
Reply to author
Forward
0 new messages