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 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法