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}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码