On Tue, Jan 19, 2021 at 10:02 PM burak serdar <[email protected]> wrote:
>
> As a generic-function writer, I do not know if the argument will be an
> interface or a concrete type. I don't want to check if it is
> zero-value, I want to check if it is nil, because I don't want it to
> panic.
Other people in this thread have made useful comments. I want to add
that this request doesn't make sense to me. A generic type has
constraints that describe exactly what operations are permitted for
values of that generic type. The current proposal provides no way to
write a constraint for "can be compared to nil". If we could write
such a constraint, then if you used it, that type parameter could not
be instantiated by a numeric type or a string type. That doesn't seem
clearly useful.
It seems to me that what you are suggesting is something like "if a
type argument is an interface type, then permit comparing with nil."
I don't think that's a useful way to program in a language like Go.
Calling a method on a nil interface value will crash in a reliable and
dependable way, just as dereferencing a nil pointer will crash. There
is no more need to check for a nil interface value than there is a
need to check for a nil pointer value.
Finally, you can call this if you really must:
func IsNilInterface[T any](v T) bool {
typ := reflect.TypeOf(&v).Elem()
if typ.Kind() != reflect.Interface {
return false
}
return reflect.ValueOf(&v).Elem().IsZero()
}
Ian
--
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 [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcVykAqBefafk%3DUF%3D_1sh0U5tjVy12QbJmOzNnXfNzhe8A%40mail.gmail.com.