golang接口demo
时间: 2023-07-26 11:16:02 浏览: 59
好的,这里有一个简单的 Go 接口示例:
```
package main
import "fmt"
// 定义一个接口
type Shape interface {
Area() float64
}
// 定义一个结构体 Circle,实现 Shape 接口
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
// 定义一个结构体 Rectangle,实现 Shape 接口
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func main() {
// 定义一个 Shape 类型的变量
var s Shape
// 将 Circle 类型的实例赋值给 s
s = Circle{Radius: 5}
fmt.Println("Circle area:", s.Area())
// 将 Rectangle 类型的实例赋值给 s
s = Rectangle{Width: 10, Height: 5}
fmt.Println("Rectangle area:", s.Area())
}
```
在上面的示例中,我们定义了一个 Shape 接口,它有一个方法 Area(),用于计算图形的面积。然后我们定义了两个结构体 Circle 和 Rectangle,它们都实现了 Shape 接口中定义的方法。最后我们定义了一个 Shape 类型的变量 s,它的值可以是 Circle 或 Rectangle 类型的实例,因为它们都实现了 Shape 接口。我们可以通过 s 变量来调用 Area() 方法,实现了多态的效果。