在Go语言中,接口(Interface)是一种抽象类型,用于定义对象的行为和方法集合,而无需关注对象的具体类型。接口定义了一组方法签名,对象只要实现了接口中的所有方法,就被认为实现了该接口。接口提供了一种松耦合的方式来编写代码,使得不同的类型可以互换使用,从而实现了多态性。
使用接口来实现不同几何形状的面积计算。
package main
import (
"fmt"
"math"
)
// 定义一个接口 Shape,包含 Area 方法
type Shape interface {
Area() float64
}
// 定义 Circle 结构体,并实现 Area 方法
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
// 定义 Rectangle 结构体,并实现 Area 方法
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func printArea(s Shape) {
fmt.Printf("Area: %f\n", s.Area())
}
func main() {
circle := Circle{Radius: 5}
rectangle := Rectangle{Width: 3, Height: 4}
// 使用接口作为函数参数,实现多态性
printArea(circle)
printArea(rectangle)
}
在这个示例中,我们首先定义了一个名为 Shape
的接口,它包含一个 Area
方法。然后,我们分别创建了 Circle
和 Rectangle
结构体,并为它们实现了 Area
方法。接着,我们定义了一个函数 printArea
,它的参数是一个实现了 Shape
接口的对象。通过将不同的几何形状对象传递给 printArea
函数,我们实现了多态性,即不同类型的对象以一致的方式进行操作。
这个示例演示了接口如何在Go中实现多态性和代码重用。通过接口,我们可以通过统一的方式处理不同类型的对象,而无需关心对象的具体类型。