在Go语言中,为了避免方法冲突,你可以采取以下几种策略:
type Rectangle struct {
width, height float64
}
func (r Rectangle) Area() float64 {
return r.width * r.height
}
type Circle struct {
radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.radius * c.radius
}
func (r Rectangle) SetWidth(width float64) (width, error) {
if width <= 0 {
return 0, errors.New("width must be greater than 0")
}
r.width = width
return r.width, nil
}
func (r Rectangle) SetHeight(height float64) (height, error) {
if height <= 0 {
return 0, errors.New("height must be greater than 0")
}
r.height = height
return r.height, nil
}
type Shape interface {
Area() float64
}
type Rectangle struct {
width, height float64
}
func (r Rectangle) Area() float64 {
return r.width * r.height
}
type Circle struct {
radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.radius * c.radius
}
type ShapeContainer struct {
shape Shape
}
func (sc ShapeContainer) Area() float64 {
return sc.shape.Area()
}
总之,要避免Go语言方法冲突,关键是根据实际需求和场景选择合适的设计策略,如使用不同的接收者类型、命名返回值或组合等。