duan2428 2012-11-20 15:21
浏览 99
已采纳

在Go中检查nil和nil接口

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

func isNil(a interface{}) bool {
  defer func() { recover() }()
  return a == nil || reflect.ValueOf(a).IsNil()
}

Since reflect.ValueOf(a).IsNil() panics if the value's Kind is anything other than Chan, Func, Map, Ptr, Interface or Slice, I threw in the deferred recover() to catch those.

Is there a better way to achieve this check? It think there should be a more straight forward way to do this.

  • 写回答

4条回答 默认 最新

  • duansan9435 2012-11-20 15:43
    关注

    See for example Kyle's answer in this thread at the golang-nuts mailing list.

    In short: If you never store (*T)(nil) in an interface, then you can reliably use comparison against nil, no need to use reflection. On the other hand, assigning untyped nil to an interface is always OK.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?