在Go语言中,接口(interface)可以实现多态性。多态性是指不同的类型可以表现出相同的行为。
要实现多态性,需要定义一个接口,并在不同的类型中实现该接口。然后,可以通过接口类型的变量来调用实现了接口的方法,从而实现多态性。
以下是实现多态性的方法:
type Shape interface {
Area() float64
Perimeter() float64
}
type Rect struct {
width float64
height float64
}
func (r Rect) Area() float64 {
return r.width * r.height
}
func (r Rect) Perimeter() float64 {
return 2 * (r.width + r.height)
}
type Circle struct {
radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.radius * c.radius
}
func (c Circle) Perimeter() float64 {
return 2 * math.Pi * c.radius
}
func printShapeInfo(s Shape) {
fmt.Println("Area:", s.Area())
fmt.Println("Perimeter:", s.Perimeter())
}
func main() {
rect := Rect{width: 5, height: 3}
circle := Circle{radius: 2}
printShapeInfo(rect)
printShapeInfo(circle)
}
在上面的示例中,Shape接口定义了两个方法Area()和Perimeter()。然后,Rect和Circle结构体分别实现了Shape接口,并提供了这两个方法的具体实现。
在main函数中,我们创建了一个Rect类型的变量rect和一个Circle类型的变量circle。然后,我们调用printShapeInfo函数,传入rect和circle,实现了多态性。printShapeInfo函数中的参数类型为Shape接口,因此可以传入任何实现了Shape接口的类型,并调用对应的方法。
最终,输出结果是Rect和Circle的面积和周长。这说明通过接口实现了多态性,不同类型的变量可以表现出相同的行为。