Go 语言中的接口
接口是 Go 语言中一个非常重要的概念,它定义了对象的行为规范。Go 的接口与其他语言的接口有所不同,它采用隐式实现的方式,更加灵活和轻量级。
接口基础
go
"math") // 定义一个 Shape 接口type Shape interface { area() float64 perimeter() float64} // Circle 结构体type Circle struct { radius float64} // 实现 Shape 接口的 area 方法func (c Circle) area() float64 { return math.Pi * c.radius * c.radius} // 实现 Shape 接口的 perimeter 方法func (c Circle) perimeter() float64 { return 2 * math.Pi * c.radius} // Rectangle 结构体type Rectangle struct { width, height float64} // 实现 Shape 接口的 area 方法func (r Rectangle) area() float64 { return r.width * r.height} // 实现 Shape 接口的 perimeter 方法func (r Rectangle) perimeter() float64 { return 2 * (r.width + r.height)} // 计算面积的函数,接受 Shape 接口类型func printArea(s Shape) { fmt.Printf("Area: %.2f\n", s.area())} // 计算周长的函数,接受 Shape 接口类型func printPerimeter(s Shape) { fmt.Printf("Perimeter: %.2f\n", s.perimeter())} func main() { c := Circle{radius: 5} r := Rectangle{width: 3, height: 4} // 通过接口调用方法 printArea(c) printPerimeter(c) printArea(r) printPerimeter(r) // 接口也可以作为变量类型 var s Shape s = c // 赋值为 Circle fmt.Println("Interface variable area:", s.area()) s = r // 赋值为 Rectangle fmt.Println("Interfa
发布于:辽宁省