Reputation: 4394
I have a generic function. I want to check if parameter provided is nil (and prevent it).
What is the best way to do it?
Here is a sample code:
func main() {
Hello(1)
}
func Hello[T any](id T) {
if reflect.ValueOf(id).IsNil() {
panic("id cannot be nil")
}
fmt.Printf("Hello %v\n", id)
}
That code panics.
Upvotes: 5
Views: 5236
Reputation: 2741
Adapted from anon's answer — checking for nils
func isNil[T any](t T) bool {
v := reflect.ValueOf(t)
kind := v.Kind()
// Must be one of these types to be nillable
return (kind == reflect.Ptr ||
kind == reflect.Interface ||
kind == reflect.Slice ||
kind == reflect.Map ||
kind == reflect.Chan ||
kind == reflect.Func) &&
v.IsNil()
}
Upvotes: 1
Reputation: 4605
For pointers this works:
func isNil[T comparable](arg T) bool {
var t T
return arg == t
}
https://go.dev/play/p/G9K3i28qGFX
Upvotes: 0
Reputation: 21
The only types that can be nil are chan, func, interface, map, pointer, and slice. Check for one of those types before calling IsNil
func Hello[T any](id T) {
if v := reflect.ValueOf(id); (v.Kind() == reflect.Ptr ||
v.Kind() == reflect.Interface ||
v.Kind() == reflect.Slice ||
v.Kind() == reflect.Map ||
v.Kind() == reflect.Chan ||
v.Kind() == reflect.Func) && v.IsNil() {
panic("id cannot be nil")
}
fmt.Printf("Hello %v\n", id)
}
Upvotes: 2