在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語言方法沖突,關鍵是根據實際需求和場景選擇合適的設計策略,如使用不同的接收者類型、命名返回值或組合等。