dsbckxk165039 2015-03-16 21:40
浏览 41
已采纳

Go中的界面如何表示?

I'm reading through two articles right now and am a little confused.

This article - http://blog.golang.org/laws-of-reflection says

> var r io.Reader
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
if err != nil {
    return nil, err
}
r = tty

r contains, schematically, the (value, type) pair, (tty, *os.File). Notice that the type *os.File implements methods other than Read; even though the interface value provides access only to the Read method, the value inside carries all the type information about that value.

This other article, says

In terms of our example, the itable for Stringer holding type Binary lists the methods used to satisfy Stringer, which is just String: Binary's other methods (Get) make no appearance in the itable.

enter image description here

It feels like these two are in opposition. According to the second article, the variable r in the first extract should be (tty, io.Reader), as that is the static type of r. Instead, the article says that *os.File is the type of tty. If the second example were right, then the diagram in the first example should have all of the methods implemented by the Binary type.

Where am I going wrong?

  • 写回答

2条回答 默认 最新

  • dongzhang7961 2015-03-16 22:03
    关注

    The two articles are explaining a similar concept at two very different levels of granularity. As Volker said, "Laws of Reflection" is a basic overview of what is actually happening when you examine objects via reflection. Your second article is examining the dynamic dispatch properties of an interface (which, can be resolved via reflection as well) and how the runtime resolves them at runtime.

    According to the second article, the variable r in the first extract should be (tty, io.Reader)

    Given that understanding, think of an interface at runtime as a "wrapper object". It exists to provide information about another object (the itable from your second article) to know where to jump to in the wrapped objects layout (implementation may differ between versions .. but the principle is basically the same for most languages).

    This is why calling Read on r works .. first it will check the itable and jump to the function that is laid out for the os.File type. If that was an interface .. you would be looking at another dereference and dispatch (which IIRC isn't applicable at all in Go).

    RE: Reflection - you're getting an easily digestible representation of this, in the form of a (value, type) pair (via the reflect.ValueOf and reflect.TypeOf methods).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题