Go 什么时候去反射接口是假的?
根据这个示例(),以及Go 什么时候去反射接口是假的?,go,reflection,Go,Reflection,根据这个示例(),以及reflect/value.go中CanInterface的实现,看起来CanInterface仅在私有字段中为false 当CanInterface为false时,还有哪些场景 游乐场示例: num := 6 meta := reflect.ValueOf(num) fmt.Println("canInterface:", meta.CanInterface() == true) meta = reflect.ValueOf(&num) fmt.Println(
reflect/value.go
中CanInterface
的实现,看起来CanInterface
仅在私有字段中为false
当CanInterface
为false时,还有哪些场景
游乐场示例:
num := 6
meta := reflect.ValueOf(num)
fmt.Println("canInterface:", meta.CanInterface() == true)
meta = reflect.ValueOf(&num)
fmt.Println("canInterface:", meta.CanInterface() == true)
foo := Foo{}
meta = reflect.ValueOf(&foo)
fmt.Println("canInterface:", meta.CanInterface() == true)
meta = meta.Elem()
fmt.Println("canInterface:", meta.CanInterface() == true)
publicField := meta.FieldByName("Number")
privateField := meta.FieldByName("privateNumber")
fmt.Println(
"canInterface:",
publicField.CanInterface() == true,
// Woah, as per the implementation (reflect/value.go)
// this is the only time it can be false
privateField.CanInterface() != true)
var fooPtr *Foo
var ptr anInterface = fooPtr
meta = reflect.ValueOf(ptr)
fmt.Println("canInterface:", meta.CanInterface() == true)
meta = reflect.ValueOf(&foo)
meta = meta.Elem() // ptr to actual value
publicField = meta.FieldByName("Number")
ptrToField := publicField.Addr()
fmt.Println("canInterface:", ptrToField.CanInterface() == true)
反射/值.go
func (v Value) CanInterface() bool {
if v.flag == 0 {
panic(&ValueError{"reflect.Value.CanInterface", Invalid})
}
// I think "flagRO" means read-only?
return v.flag&flagRO == 0
}
如果您深入研究,您可以看到这条线:
return v.flag&flagRO == 0
下面是函数valueInterface
中的这段代码:
if safe && v.flag&flagRO != 0 {
// Do not allow access to unexported values via Interface,
// because they might be pointers that should not be
// writable or methods or function that should not be callable.
panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
}
自
v.flag&flagRO!=0
相当于!CanInterface
,我们可以从下面的注释中得出结论,当reflect.Value
是未报告的结构字段或方法时,CanInterface
为false。您知道meta.CanInterface()==true
与meta.CanInterface()
完全相同,对吗?:)