在Go语言中,多态可以通过接口和类型断言来实现。
使用接口实现多态:定义一个接口,包含多个方法。
type Animal interface { Sound() string}定义多个结构体,并实现接口的方法。
type Dog struct{}func (d Dog) Sound() string { return "汪汪汪"}type Cat struct{}func (c Cat) Sound() string { return "喵喵喵"}使用多态:
func main() { animals := []Animal{Dog{}, Cat{}} for _, animal := range animals { fmt.Println(animal.Sound()) }}使用类型断言实现多态:定义一个接口,可以为空接口interface{},表示任意类型。
type Animal interface { Sound() string}定义多个结构体,并实现接口的方法。
type Dog struct{}func (d Dog) Sound() string { return "汪汪汪"}type Cat struct{}func (c Cat) Sound() string { return "喵喵喵"}使用多态:
func main() { animals := []interface{}{Dog{}, Cat{}} for _, animal := range animals { if a, ok := animal.(Animal); ok { fmt.Println(a.Sound()) } }}以上两种方法都可以实现多态,具体使用哪种方法取决于实际需求和代码设计。

