interface中保存着对象的类型和指向值的指针。但要注意,在创建interface对象时,指向对象的类型需要精确指定,而不能依靠自动识别。
package main
import "fmt"
func main() {
var b *Base = new(Child).Create().GetBase()
b.Foo() // Sub.Foo is called
}
type IMatch interface {
Create() IMatch
GetBase() *Base
Foo()
}
type Base struct {
internal IMatch
}
type Child struct {
Base
}
// abstract
func (this *Base) Create() IMatch {
panic("Base.Create() should not be called")
return this
}
func (this *Base) GetBase() *Base {
return this
}
func (this *Base) Foo() {
if this.internal != nil {
this.internal.Foo()
}
}
func (this *Child) Create() IMatch {
this.internal = this
return this
}
func (this *Child) Foo() {
fmt.Println("Child.Foo is called")
}