在Go语言中,接口多态是通过接口类型和实现了该接口的具体类型的组合来实现的。接口多态允许我们编写更加灵活和可扩展的代码,因为我们可以将不同的实现类型传递给相同的接口变量,而无需关心具体的实现细节。
要实现接口多态,需要遵循以下步骤:
type Shape interface {
    Area() float64
}
type Circle struct {
    Radius float64
}
func (c Circle) Area() float64 {
    return math.Pi * c.Radius * c.Radius
}
type Rectangle struct {
    Width, Height float64
}
func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}
func PrintArea(s Shape) {
    fmt.Println("Area:", s.Area())
}
func main() {
    c := Circle{Radius: 5}
    r := Rectangle{Width: 4, Height: 6}
    PrintArea(c) // 输出:Area: 78.53981633974483
    PrintArea(r) // 输出:Area: 24
}
在这个例子中,我们定义了一个名为Shape的接口,它包含一个名为Area的方法。然后,我们创建了两个实现了Shape接口的具体类型:Circle和Rectangle。最后,我们编写了一个名为PrintArea的函数,它接受一个Shape类型的参数,并调用其Area方法。在main函数中,我们分别使用Circle和Rectangle类型的值调用PrintArea函数,实现了接口多态。