dongyao5186 2016-01-12 21:35
浏览 27
已采纳

为什么将接口嵌入结构中会导致将接口方法集定义为nil指针?

I'm working through learning Go, and I've come across embedding Interfaces into structs in Go.

I understand the joys of Interfaces and their implementations, but I'm confused as the reasoning for the current execution of embedding one inside a struct.

When I embed an interface in a struct, the struct gains the methodset of the Interface and can now be used as a value of an Interface type variable, eg:

type Foo interface {
  SetBaz(baz) 
  GetBaz() baz
}

type Bar struct {
  Foo
}

So now we have a struct type Bar which embeds Foo. Because Bar embeds Foo, Bar now satisfies any receivers or arguments that require type Foo, even though Bar hasn't even defined them.

Trying to call Bar.GetBaz() causes the runtime error: panic: runtime error: invalid memory address or nil pointer dereference.

Why does Go define nil methods on a struct that embeds an interface instead of explicitly requiring those methods to be defined through the compiler?

  • 写回答

1条回答 默认 最新

  • drplww2505 2016-01-12 21:55
    关注

    You're wrong about the nil method, it's the interface embedded into the struct Bar that is nil. When you use the methods of the interface, that is this interface that is called. The trick allow you to override an interface method with our own.

    To understand the usage and goals of embedding interfaces into struct, the best example is in the sort package:

    type reverse struct {
        // This embedded Interface permits Reverse to use the methods of
        // another Interface implementation.
        Interface
    }
    
    // Less returns the opposite of the embedded implementation's Less method.
    func (r reverse) Less(i, j int) bool {
        return r.Interface.Less(j, i)
    }
    
    // Reverse returns the reverse order for data.
    func Reverse(data Interface) Interface {
        return &reverse{data}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像