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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?