Go语言自定义方法约束 官网
在Go语言里,自定义方法约束可让类型实现特定方法。比如定义接口,类型实现接口方法。 package mainimport "fmt"// 定义接口 type Shape interface { Area() float64}// 定义结构体 type Rectangle struct { Width float64 Height float64}// 实现接口方法 func (r Rectangle) Area() float64 { return r.Width * r.Height}func main() { rect := Rectangle{Width: 5, Height: 3} fmt.Println(rect.Area()) // 运行结果: 15} 注意接口定义和方法实现签名要一致。