Go 通过接口来实现多态。在 Go 语言中,我们是隐式地实现接口。一个类型如果定义了接口所声明的全部方法,那它就实现了该接口。现在我们来看看,利用接口,Go 是如何实现多态的。
package mainimport "fmt"type Income interface {Money() intSize() string
}type GetSize struct {Name stringAge int
}type GetNum struct {Name stringAge int
}func (p GetSize) Money() int {return p.Age
}func (p GetSize) Size() string {return p.Name
}func (p GetNum) Money() int {return p.Age
}func (p GetNum) Size() string {return p.Name
}func main() {project1 := GetSize{Name: "bob",Age: 20,}project2 := GetNum{Name: "jack",Age: 29,}p := []Income{project1, project2}for _, val := range p {m := val.Money()fmt.Println(m)}
}