go nil转为interface{}后判断不可靠

判断一个值是否为nil,最好是直接跟nil进行比较判断,而不要通过interface{}的形参传给另一个函数来进行判断。 

但是用反射可以通过interface{}来判断nil,如testnil5。
看如下示例代码,a是一空指针,但只有testnil4和testnil5能正确判断出来:

type State struct {}

func testnil1(a, b interface {}) bool {
      return a == b
}

func testnil2(a *State, b interface{}) bool{
      return a == b
}

func testnil3(a interface {}) bool {
      return a == nil
}

func testnil4(a *State) bool {
      return a == nil
}

func testnil5(a interface {}) bool {
      v := reflect.ValueOf(a)
      return !v.IsValid() || v.IsNil()
}

func main(){
      var a *State
      fmt.Println(a)

      fmt.Println(testnil1(a, nil))
      fmt.Println(testnil2(a, nil))
      fmt.Println(testnil3(a))
      fmt.Println(testnil4(a))
      fmt.Println(testnil5(a))
}

 

输出结果为:

<nil>
false
false
false
true
true

 

posted on 2018-12-10 16:00  &大飞  阅读(358)  评论(0编辑  收藏  举报

导航