duangouhui0446 2017-04-08 00:46
浏览 43

struct第一行只是一个接口,这是什么意思? [重复]

This question already has an answer here:

I come across this code in Go:

type Mytype struct {
  Interfacename
  var1  ClientInterface1
  var2  ClientInterface2
  id    int
}

What does that first field mean?

</div>
  • 写回答

1条回答 默认 最新

  • douxianji6181 2017-04-08 01:30
    关注

    Mostly, this is how some sort of inheritance (by composition rather than inheritance) is achieved in go. Check this out: https://golang.org/doc/effective_go.html#embedding

    This will grant the Outer type (MyType) access to this inner type's Receiver methods (the assigned struct{} since this is an interface).

    From Go Effective:

    There's an important way in which embedding differs from subclassing. When we embed a type, the methods of that type become methods of the outer type, but when they are invoked the receiver of the method is the inner type, not the outer one

    Thanks @Flimzy and @md2perpe

    Also, this defines an anonymous field, for which the variable name will be the same as its type name.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大