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 :)

https://go2goplay.golang.org/p/-nDAUVYWuxo



On Tue, 23 Jun 2020 at 05:43, 'Bryan C. Mills' via golang-nuts <
golang-nuts@googlegroups.com> wrote:

> 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?
>
> --
> 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+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/CAKWVi_SED7FvqerjhzX8OBss3MHzbb3aw%2BLOcRcC3Lf3GUZCfw%40mail.gmail.com
> <https://groups.google.com/d/msgid/golang-nuts/CAKWVi_SED7FvqerjhzX8OBss3MHzbb3aw%2BLOcRcC3Lf3GUZCfw%40mail.gmail.com?utm_medium=email&utm_source=footer>
> .
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAJhgacirMen54vZw7SnUHvM2DtADm9fnjF3dMziATnC4WvcmaQ%40mail.gmail.com.

Reply via email to