Go 接口的动态性 代码示范

5 min read

package main

import (
"fmt"
)

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

// 定义一个结构体(矩形)
type Rectangle struct {
width, height float64
}

// 实现Shape接口中的area方法
func (r Rectangle) area() float64 {
return r.width * r.height
}

// 定义一个结构体(圆形)
type Circle struct {
radius float64
}

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

// 打印形状的面积
func printArea(s Shape) {
fmt.Println(s.area())
}

func main() {
// 创建一个矩形对象
r := Rectangle{10, 20}
// 创建一个圆形对象
c := Circle{5}
// 打印矩形的面积
printArea(r)
// 打印圆形的面积
printArea(c)
}

// 输出结果:
// 200
// 78.5