golang 中接口的应用
package main
import "fmt"
type gameObject struct {
name string
}
func (o *gameObject) Name() string{
return o.name
}
func (o *gameObject) Attack() {
fmt.Printf("GameObject %s do not know how to attack\n", o.name)
}
type player struct {
gameObject
}
func (p *player) Attack(){
fmt.Printf("player %s attacks\n", p.name)
}
type monster struct {
gameObject
}
type challenger interface {
Name() string Attack()
}
func main(){
p := &player{gameObject : gameObject{name:"devgl"}}
m := &monster{gameObject : gameObject{name:"slime"}}
Attack(p) Attack(m)
}
func Attack(c challenger) {
c.Attack()
}
输出:
player devgl attacks
GameObject slime do not know how to attack
上面这段代码声明了两个内嵌gameObject自定义类型player和monster,其中,gameObject实现了challenger接口的所有函数,因此gameObject实现了challenger接口,那么,我们可以说player和monster这两个自定义类型也实现了该接口。除此之外,player类型定义了自己的Attack函数实现,在main函数中,我们创建了p,m两个对象分别对应player和monster,并将对象的指针传入Attack全局函数。这里可以注意到Attack全局函数的参数是一个challenger接口,而player,monster都实现了这个接口,所以这样传值没有问题,程序输出: