如何检查泛型类型是否为nil

huangapple go评论69阅读模式
英文:

How to check if generic type is nil

问题

我有一个通用函数。我想检查提供的参数是否为nil(并防止它)。

最好的方法是什么?

以下是示例代码:

func main() {
	Hello(1)
}

func Hello[T any](id T) {
	if reflect.ValueOf(id).IsNil() {
		panic("id不能为nil")
	}
	fmt.Printf("Hello %v\n", id)
}

该代码会引发panic。

英文:

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.

答案1

得分: 2

对于指针,这段代码可以工作:

func isNil[T comparable](arg T) bool {
	var t T
	return arg == t
}

链接:https://go.dev/play/p/G9K3i28qGFX

英文:

For pointers this works:

func isNil[T comparable](arg T) bool {
	var t T
	return arg == t
}

https://go.dev/play/p/G9K3i28qGFX

答案2

得分: 0

只有 chan、func、interface、map、pointer 和 slice 类型可以为 nil。在调用 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)
}
英文:

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

huangapple
  • 本文由 发表于 2022年10月5日 13:52:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/73956346.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定