Go is 不是(完全)面向对象的语言 http://golang.org/doc/faq#Is_Go_an_object-oriented_language:它没有类并且它没有类型继承 http://golang.org/doc/faq#inheritance;但它支持类似的构造,称为嵌入都在struct
水平和interface
水平,并且确实有methods http://golang.org/ref/spec#Method_declarations.
接口 http://golang.org/ref/spec#Interface_types在 Go 中只是固定的方法集。一种隐含地如果其方法集是接口的超集(没有意图声明),则实现接口。
如果你愿意的话,空方法是很好的选择document or 明确说明您的类型确实实现了一个接口(因为没有明确说明)。官方的Go 常见问题解答:如何保证我的类型满足接口? https://golang.org/doc/faq#guarantee_satisfies_interface
type Fooer interface {
Foo()
ImplementsFooer()
}
如果您希望类型层次结构有所区别(例如,您不想允许一个对象既是Movable
and Immovable
),它们必须有不同的方法集(每个方法集中必须至少有 1 个方法Movable
and Immovable
这在其他方法中不存在),因为如果方法集包含相同的方法,一个方法的实现也会自动实现另一个方法,因此您可以分配一个Movable
对象类型的变量Immovable
.
假设您不会将此类方法添加到其他类型,则向具有相同名称的接口添加空方法将为您提供这种区别。
减少空方法的数量
就我个人而言,我对空方法没有任何问题。不过有一种方法可以减少它们。
如果您还创建了一个struct
执行对于层次结构中的每种类型和每种实现embeds the struct
实现高一级,高一级的方法集就会自动来了:
Object
Object
接口和ObjectImpl
执行:
type Object interface {
object()
}
type ObjectImpl struct {}
func (o *ObjectImpl) object() {}
不动产
Immovable
接口和ImmovableImpl
执行:
type Immovable interface {
Object
immovable()
}
type ImmovableImpl struct {
ObjectImpl // Embed ObjectImpl
}
func (o *Immovable) immovable() {}
Note ImmovableImpl
只添加immovable()
方法,object()
是“继承”的。
Building
Building
执行:
type Building struct {
ImmovableImpl // Embed ImmovableImpl struct
// Building-specific other fields may come here
}
Note Building
不添加任何新方法,但它会自动成为Immovable
object.
如果“子类型”的数量增加或者接口类型具有不止 1 个“标记”方法(因为所有方法都是“继承的”),则该技术的优势会大大增加。