温馨提示×

golang interface多态怎么实现

小亿
77
2023-10-31 12:01:19
栏目: 编程语言

在Go语言中,通过接口可以实现多态。接口是一种抽象类型,它定义了一组方法的签名。任何类型只要实现了接口中定义的方法,就可以被看作是该接口的实现类型。

下面是一个示例,展示了如何在Go语言中实现多态:

package main

import "fmt"

// 定义一个接口
type Shape interface {
    Area() float64
}

// 定义一个结构体,表示矩形
type Rectangle struct {
    Width  float64
    Height float64
}

// 实现接口中的方法
func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

// 定义一个结构体,表示圆形
type Circle struct {
    Radius float64
}

// 实现接口中的方法
func (c Circle) Area() float64 {
    return 3.14 * c.Radius * c.Radius
}

func main() {
    // 创建一个矩形对象
    rectangle := Rectangle{Width: 10, Height: 5}
    // 创建一个圆形对象
    circle := Circle{Radius: 5}

    // 利用接口实现多态
    shapes := []Shape{rectangle, circle}

    // 遍历shapes,调用不同类型的Area方法
    for _, shape := range shapes {
        fmt.Println(shape.Area())
    }
}

在上面的示例中,我们定义了一个Shape接口,并在RectangleCircle结构体中实现了该接口的方法。然后我们创建了一个shapes切片,其中包含了一个矩形和一个圆形对象。接着,利用接口实现了多态,通过遍历shapes切片,调用不同类型的Area方法。

输出结果为:

50
78.5

可以看到,虽然shapes切片中的元素类型不同,但是通过接口实现了多态,可以调用不同类型的方法。

0