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 == nil
的结果是false
?
*string
,所以v.(*string) == nil
才能起作用。 - OneOfOne