[generics] constraint for nillable types?

123 views
Skip to first unread message

Bryan C. Mills

unread,
Jun 23, 2020, 12:43:30 AM6/23/20
to golang-nuts
I tried writing a generic “FirstNonNil” function, but got stuck at the "== nil" part.

First I thought to maybe add a type list enumerating all of the nillable types, but I don't have a way to enumerate all of the possible interface types as part of that list, and there is no constraint for “any interface type”.

Then I thought I could use a `var zero T` variable and compare `== zero` instead of `== nil`. But that doesn't work either: I need the `comparable` constraint to get `==`, but not every nillable type is comparable with an arbitrary variable (slices, maps, and functions are not).

So it seems that the best I can do is to write a generic `First` function and make the caller write out `func (x T) bool { return x != nil }` explicitly at every call site. Did I miss a better option?

roger peppe

unread,
Jun 23, 2020, 4:02:41 AM6/23/20
to Bryan C. Mills, golang-nuts
FWIW I also came across this issue recently in a different context and similarly wondered if a nillable constraint might be a good idea.

There is a kinda workaround although you won't like it :)




--
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/CAKWVi_SED7FvqerjhzX8OBss3MHzbb3aw%2BLOcRcC3Lf3GUZCfw%40mail.gmail.com.

jimmy frasche

unread,
Jun 23, 2020, 11:44:43 AM6/23/20
to roger peppe, Bryan C. Mills, golang-nuts
One way is https://github.com/golang/go/issues/26842 which is to
provide some mechanism to compare any value with its type's zero value
(either with a universal zero value or something like isZero(v)). That
removes all the special cases so you could use it even without any
constraints
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAJhgacirMen54vZw7SnUHvM2DtADm9fnjF3dMziATnC4WvcmaQ%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages