gpt4 book ai didi

go - 什么时候 go reflect CanInterface false?

转载 作者:IT王子 更新时间:2023-10-29 02:09:51 27 4
gpt4 key购买 nike

根据这个 playground 示例(https://play.golang.org/p/Jr64yE4zSpQ),以及 reflect/value.goCanInterface 的实现,它看起来像 CanInterface 仅对私有(private)字段为 false?

CanInterface 为 false 时还有哪些场景?

Playground 示例:

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
}

最佳答案

如果您深入了解 source code for CanInterface ,你可以看到这一行:

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,我们可以从下面的注释中得出结论,当 CanInterface 为 false 时reflect.Value 是未导出的结构字段或方法。

关于go - 什么时候 go reflect CanInterface false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50279840/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com