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

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

How to check if generic type is nil

问题

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

最好的方法是什么?

以下是示例代码:

  1. func main() {
  2. Hello(1)
  3. }
  4. func Hello[T any](id T) {
  5. if reflect.ValueOf(id).IsNil() {
  6. panic("id不能为nil")
  7. }
  8. fmt.Printf("Hello %v\n", id)
  9. }

该代码会引发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:

  1. func main() {
  2. Hello(1)
  3. }
  4. func Hello[T any](id T) {
  5. if reflect.ValueOf(id).IsNil() {
  6. panic("id cannot be nil")
  7. }
  8. fmt.Printf("Hello %v\n", id)
  9. }

That code panics.

答案1

得分: 2

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

  1. func isNil[T comparable](arg T) bool {
  2. var t T
  3. return arg == t
  4. }

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

英文:

For pointers this works:

  1. func isNil[T comparable](arg T) bool {
  2. var t T
  3. return arg == t
  4. }

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

答案2

得分: 0

只有 chan、func、interface、map、pointer 和 slice 类型可以为 nil。在调用 IsNil 之前,请检查这些类型之一。

  1. func Hello[T any](id T) {
  2. if v := reflect.ValueOf(id); (v.Kind() == reflect.Ptr ||
  3. v.Kind() == reflect.Interface ||
  4. v.Kind() == reflect.Slice ||
  5. v.Kind() == reflect.Map ||
  6. v.Kind() == reflect.Chan ||
  7. v.Kind() == reflect.Func) && v.IsNil() {
  8. panic("id cannot be nil")
  9. }
  10. fmt.Printf("Hello %v\n", id)
  11. }
英文:

The only types that can be nil are chan, func, interface, map, pointer, and slice. Check for one of those types before calling IsNil

  1. func Hello[T any](id T) {
  2. if v := reflect.ValueOf(id); (v.Kind() == reflect.Ptr ||
  3. v.Kind() == reflect.Interface ||
  4. v.Kind() == reflect.Slice ||
  5. v.Kind() == reflect.Map ||
  6. v.Kind() == reflect.Chan ||
  7. v.Kind() == reflect.Func) && v.IsNil() {
  8. panic("id cannot be nil")
  9. }
  10. fmt.Printf("Hello %v\n", id)
  11. }

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:

确定