【发布时间】:2021-08-21 16:40:49
【问题描述】:
我想为接口创建可选的 perim mehtod。有可能吗?就像我不想为三角形创建 perim 方法,但它给了我一个错误,即缺少一种方法。接口中是否可以有可选方法?
请告诉我它的替代方案或解决方案。
type geometry interface {
area() float64
perim() float64
}
type rect struct {
width, height float64
}
type triangle struct {
base, height float64
}
type circle struct {
radius float64
}
type square struct {
side float64
}
func (r rect) area() float64 {
return r.width * r.height
}
func (r rect) perim() float64 {
return 2*r.width + 2*r.height
}
func (c circle) area() float64 {
return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
return 2 * math.Pi * c.radius
}
func (t triangle) area() float64 {
return 1 / 2 * t.base * t.height
}
func measure(g geometry) {
fmt.Println(g)
switch g.(type) {
case rect:
fmt.Println("Rectangles area :", g.area())
fmt.Println("Rectangle perimeter: ", g.perim())
case circle:
fmt.Printf("Circles Area: %.2f\n", g.area())
fmt.Printf("Circles Perimeter: %.2f\n", g.perim())
case square:
fmt.Printf("Area of square: %.2f\n", g.area())
fmt.Printf("Perimeters of area: %.2f\n", g.perim())
case triangle:
fmt.Printf("Area of triangle: %.2f\n", g.area())
}
}
func main() {
r := rect{width: 3, height: 4}
c := circle{radius: 5}
s := square{side: 7}
t := triangle{base: 3, height: 4}
measure(r)
measure(c)
measure(s)
measure(t)
}
【问题讨论】:
-
是的 g 是接口所以我可以使用空接口概念吗?