温馨提示×

go语言中的type如何定义接口

小樊
98
2024-12-12 08:14:49
栏目: 编程语言

在 Go 语言中,接口是一种抽象类型,它定义了一组方法,但它不会实现这些方法。任何实现了接口中所有方法的类型都可以被认为实现了该接口。要在 Go 中定义接口,请使用关键字 type 和接口名称,然后在括号内指定接口的方法列表。方法列表使用大括号 {} 包围,每个方法由返回类型、方法名称、参数列表和方法体组成。这里有一个简单的示例:

package main import "fmt" // 定义一个名为 Shape 的接口,包含两个方法:Area 和 Perimeter type Shape interface { Area() float64 Perimeter() float64 } // 定义一个名为 Circle 的结构体,表示一个圆形 type Circle struct { Radius float64 } // 为 Circle 结构体实现 Shape 接口的 Area 方法 func (c Circle) Area() float64 { return 3.14 * c.Radius * c.Radius } // 为 Circle 结构体实现 Shape 接口的 Perimeter 方法 func (c Circle) Perimeter() float64 { return 2 * 3.14 * c.Radius } // 定义一个名为 Rectangle 的结构体,表示一个矩形 type Rectangle struct { Width, Height float64 } // 为 Rectangle 结构体实现 Shape 接口的 Area 方法 func (r Rectangle) Area() float64 { return r.Width * r.Height } // 为 Rectangle 结构体实现 Shape 接口的 Perimeter 方法 func (r Rectangle) Perimeter() float64 { return 2 * (r.Width + r.Height) } func main() { // 创建一个 Shape 类型的切片,用于存储不同类型的 Shape 对象 var shapes []Shape // 向切片中添加一个 Circle 对象 shapes = append(shapes, Circle{Radius: 5}) // 向切片中添加一个 Rectangle 对象 shapes = append(shapes, Rectangle{Width: 3, Height: 4}) // 遍历切片并调用每个对象的 Area 和 Perimeter 方法 for _, shape := range shapes { fmt.Printf("Area: %v, Perimeter: %v\n", shape.Area(), shape.Perimeter()) } } 

在这个示例中,我们定义了一个名为 Shape 的接口,它包含两个方法:Area()Perimeter()。然后,我们定义了两个结构体:CircleRectangle,并为它们实现了 Shape 接口的所有方法。最后,我们在 main 函数中创建了一个 Shape 类型的切片,并将 CircleRectangle 对象添加到切片中。通过遍历切片并调用每个对象的 Area()Perimeter() 方法,我们可以看到不同类型的对象都可以使用相同的接口类型。

0