簡體   English   中英

go 何時反映 CanInterface false?

[英]When is go reflect CanInterface false?

根據這個游樂場示例 ( https://play.golang.org/p/Jr64yE4zSpQ ),以及CanInterfacereflect/value.go中的實現,看起來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
}

如果深入研究CanInterface的源代碼,您會看到這一行:

return v.flag&flagRO == 0

在它的下方,這段代碼來自 function 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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM