如何判断golang的零值反映

时间:2016-03-11 02:38:17

标签: reflection go zero

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var p1 *string = nil
    var v interface{} = p1
    val := reflect.Indirect(reflect.ValueOf(v))
    if v == nil {
        fmt.Printf("NULL")
    } else {
        if val.CanInterface() {
            fmt.Printf("if is %v\n", val.Interface())
        }
    }
}

该程序的输出是:

···

panic: reflect: call of reflect.Value.CanInterface on zero Value

goroutine 1 [running]:
panic(0xd65a0, 0xc82005e000)
    /usr/local/go/src/runtime/panic.go:464 +0x3e6
reflect.Value.CanInterface(0x0, 0x0, 0x0, 0x0)
    /usr/local/go/src/reflect/value.go:897 +0x62

···

问题是什么?为什么v == nilfalse

1 个答案:

答案 0 :(得分:10)

v不是零,它包含*string

但是,如果要检查反射值是否有效(非零),可以使用val.IsValid()进行检查。

此外,如果您想检查它是否为零,您可以查看if val.Kind() == reflect.Ptr && val.IsNil() {}

一个小小的演示:

func main() {
    var p1 *string = nil
    var v interface{} = p1
    // this will return an invalid value because it will return the Elem of a nil pointer.
    //val := reflect.Indirect(reflect.ValueOf(v))
    val := reflect.ValueOf(v) // comment this to see the difference.
    if !val.IsValid() {
        fmt.Printf("NULL")
    } else {
        if val.CanInterface() {
            fmt.Printf("if is %#+v (%v)\n", val.Interface(), val.Interface() == nil)
        }
    }
    fmt.Println(v.(*string) == nil)
}

playground