在Go语言中,多态是通过接口实现的。下面是一个简单的示例代码,展示了多态的应用:
package main
import "fmt"
type Animal interface {
Sound() string
}
type Dog struct{
}
func (d Dog) Sound() string {
return "Woof!"
}
type Cat struct{
}
func (c Cat) Sound() string {
return "Meow!"
}
func MakeSound(a Animal) {
fmt.Println(a.Sound())
}
func main() {
animals := []Animal{
Dog{
}, Cat{
}}
for _, animal := range animals {
MakeSound(animal)
}
}
在上述代码中,定义了一个Animal
接口,该接口包含了一个Sound
方法。然后,我们实现了Dog
和Cat
结构体,它们分别实现了Animal
接口的Sound
方法。
接着,我们定义了一个MakeSound
函数,该函数接收一个Animal
类型的参数,并调用该参数的Sound
方法输出动物的声音。
在main
函数中,我们创建了一个包含Dog
和Cat
实例的animals
切片。然后,使用for
循环遍历animals
切片,将每个动物对象作为参数传递给MakeSound
函数,并输出相应的声音。
运行上述代码,输出结果为:
Woof!
Meow!
可以看到,在调用MakeSound
函数时,我们传递了不同类型的动物对象(Dog
和Cat
),但是通过接口的多态性,可以在运行时动态调用每个对象的Sound
方法,并输出不同的声音。这就是Go语言中通过接口实现的多态性。