dongshi9407 2018-05-10 19:03
浏览 109
已采纳

什么时候去反映CanInterface错误?

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
}
  • 写回答

1条回答 默认 最新

  • duanrong6802 2018-05-10 19:13
    关注

    If you dive into the source code for CanInterface, you can see this line:

    return v.flag&flagRO == 0
    

    And a bit below it, this block of code from the 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")
    }
    

    Since v.flag&flagRO != 0 is equivalent to !CanInterface, we can conclude from the comment below it that CanInterface is false when the reflect.Value is an unexported struct field or method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度