我正在学习 Go,并且遇到过将接口嵌入到 Go 结构中的情况。
我理解接口及其实现的乐趣,但我对当前执行将接口嵌入到结构中的推理感到困惑。
当我将接口嵌入到结构中时,该结构将获得接口的方法集,并且现在可以用作接口类型变量的值,例如:
type Foo interface {
SetBaz(baz)
GetBaz() baz
}
type Bar struct {
Foo
}
Run Code Online (Sandbox Code Playgroud)
所以现在我们有一个Bar嵌入的结构类型Foo。因为Barembeds Foo,Bar现在满足任何需要 type 的接收者或参数Foo,即使甚至Bar还没有定义它们。
尝试调用Bar.GetBaz()会导致运行时错误:panic: runtime error: invalid memory address or nil pointer dereference。
为什么 Go 在嵌入接口的结构体上定义 nil 方法,而不是显式要求通过编译器定义这些方法?
你的方法是错误的nil,它是interface嵌入到struct Bar的nil。当您使用接口的方法时,即调用该接口。这个技巧允许你用我们自己的方法覆盖接口方法。
interfaces要了解嵌入到的用法和目标struct,最好的例子是在sort包中:
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}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1271 次 |
| 最近记录: |