温馨提示×

golang interface多态实现的方法是什么

小亿
87
2024-01-10 09:50:48
栏目: 编程语言

在Go语言中,接口(interface)可以实现多态性。多态性是指不同的类型可以表现出相同的行为。

要实现多态性,需要定义一个接口,并在不同的类型中实现该接口。然后,可以通过接口类型的变量来调用实现了接口的方法,从而实现多态性。

以下是实现多态性的方法:

  1. 定义接口:首先需要定义一个接口,并在接口中声明需要实现的方法。
type Shape interface {
    Area() float64
    Perimeter() float64
}
  1. 实现接口:在不同的类型中实现接口,并提供方法的具体实现。
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
}
  1. 使用多态性:通过接口类型的变量来调用实现了接口的方法。
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()。然后,RectCircle结构体分别实现了Shape接口,并提供了这两个方法的具体实现。

main函数中,我们创建了一个Rect类型的变量rect和一个Circle类型的变量circle。然后,我们调用printShapeInfo函数,传入rectcircle,实现了多态性。printShapeInfo函数中的参数类型为Shape接口,因此可以传入任何实现了Shape接口的类型,并调用对应的方法。

最终,输出结果是RectCircle的面积和周长。这说明通过接口实现了多态性,不同类型的变量可以表现出相同的行为。

0