douyu8187 2015-04-30 15:09
浏览 89
已采纳

接口与指针到接口的Golang反射

In the example of gob usage http://golang.org/src/encoding/gob/example_interface_test.go they provide the following thesis: Pass pointer to interface so Encode sees (and hence sends) a value of interface type. If we passed p directly it would see the concrete type instead. See the blog post, "The Laws of Reflection" for background.

I've read The Laws of reflection twice, and a related Russ Cox article too. But I can't find a distinction between pointer-to-interface and interface there.

So why is it that through the pointer it sees a value of interface type, and with no pointer it sees (surprisingly to me) the concrete type?

  • 写回答

1条回答 默认 最新

  • dongyu5104 2015-04-30 16:05
    关注

    It seems to me that the relevant part is this:

    Continuing, we can do this:

    var empty interface{}
    empty = w
    

    and our empty interface value empty will again contain that same pair, (tty, *os.File). That's handy: an empty interface can hold any value and contains all the information we could ever need about that value.

    (emphasis added)

    When you assign an interface value to a value of type interface{}, the "pointer to data" part of the new value doesn't point to the old value, but rather to the data old value was pointing to. We can prove that with a bit of unsafe code:

    type iface struct {
        Type, Data unsafe.Pointer
    }
    
    var r io.Reader = &bytes.Buffer{}
    var i interface{} = r
    
    rr := *(*iface)(unsafe.Pointer(&r))
    ii := *(*iface)(unsafe.Pointer(&i))
    
    fmt.Printf("%v
    ", ii.Data == rr.Data) // Prints true.
    

    On the other hand, if we use a pointer, it will point to the interface value itself. So now reflect can actually see, what interface exactly are we talking about. E.g.:

    var i2 interface{} = &r
    ii2 := *(*iface)(unsafe.Pointer(&i2))
    fmt.Printf("%v
    ", ii2.Data == unsafe.Pointer(&r)) // Prints true.
    

    Playground: http://play.golang.org/p/0ZEMdIFhIj

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看