As per this playground example (https://play.golang.org/p/Jr64yE4zSpQ), and the implementation of CanInterface
in reflect/value.go
, it looks like CanInterface
is false only for private fields?
What are other scenarios when CanInterface
is false?
Playground example:
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)
reflect/value.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
}
Aucun commentaire:
Enregistrer un commentaire