2.4. 常用注意事项 9:结构体实现接口interface
g g study,d d up!
常用注意事项 9:结构体实现接口interface
9. 结构体可以实现接口,这意味着结构体类型可以与该接口类型相容,并可以使用接口变量调用接口中定义的方法。
下面是一个简单的示例,展示了如何在 Go 中实现接口。
package main
import (
"fmt"
"math"
)
// 定义一个接口
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 math.Pi * c.radius * c.radius
}
func main() {
r := Rectangle{3, 4}
c := Circle{5}
// 定义一个 Shape 类型的变量
var s Shape
// 把 Rectangle 实例赋值给 s 变量
s = r
fmt.Println("Rectangle area:", s.area())
// 把 Circle 实例赋值给 s 变量
s = c
fmt.Println("Circle area:", s.area())
}
输出结果为:
Rectangle area: 12
Circle area: 78.53981633974483
在上面的示例中,我们定义了一个 Shape
接口,它包含一个 area()
方法。然后我们定义了两个结构体,Rectangle
和 Circle
,并为它们实现了 area()
方法。接下来,我们在 main()
函数中定义了一个 Shape
类型的变量 s
,并将它赋值为一个 Rectangle
实例和一个 Circle
实例。最后,我们调用了 s
的 area()
方法,它会自动调用与 s
的类型相对应的 area()
方法。
欢迎关注公众号上海php自学中心,一起交流。