Check for nil and nil interface in Go

后端 未结 4 1309
生来不讨喜
生来不讨喜 2020-12-07 18:48

Currently I\'m using this helper function to check for nil and nil interfaces

func isNil(a interface{}) bool {
  defer func() { recover() }()
  return a == n         


        
4条回答
  •  盖世英雄少女心
    2020-12-07 19:00

    If neither of the earlier options works for you, the best I could came up so far is:

    if c == nil || (reflect.ValueOf(c).Kind() == reflect.Ptr && reflect.ValueOf(c).IsNil())
    

    At least it detects (*T)(nil) cases.

提交回复
热议问题