题目
定义 Shape 接口,包含 Area() 与 Perimeter() 两个方法,并为 Circle 和 Rectangle 实现该接口。公开样例 Circle{radius:5} 期望面积约 78.54、周长约 31.42;隐藏用例包含矩形和小圆。
- 输入契约:一个
Shape接口值,实际类型为 Circle 或 Rectangle。 - 输出契约:由具体实现计算出的面积与周长。
解题思路
Go 接口是方法集合,类型只要实现了全部方法就自动满足接口,不需要 implements 声明。这种结构化类型让调用方依赖行为而不是具体类型:接受 Shape 的函数可以同时处理圆和矩形。Circle 用 math.Pi * r * r 计算面积、2 * math.Pi * r 计算周长;Rectangle 用宽乘高、以及 2 * (w + h)。所有方法使用值接收者,因此值和指针都能满足接口。
参考实现要点
- 声明
type Shape interface { Area() float64; Perimeter() float64 }。 Circle以Radius float64为字段,两个方法均使用(c Circle)值接收者。Rectangle以Width, Height float64为字段,实现同样的两个方法。- 方法内部只读取字段并返回 float64,不修改接收者,因此值接收者语义清晰。
- 任何接收
Shape的函数都可以对两种类型执行相同调用,实现多态分派。
常见错误
- 只实现 Area 而漏掉 Perimeter,赋值给 Shape 时编译失败,错误信息会指出缺少方法。
- 混用值接收者与指针接收者,导致
Circle{}能满足接口而Rectangle{}只能以&Rectangle{}满足;同一类型的方法集应保持一致。 - 在方法中修改值接收者的字段并期待影响原对象;值接收者操作的是副本,需要指针接收者才能修改。
验证方式
分别用 Circle 和 Rectangle 作为 Shape 传入同一个函数,核对面积与周长数值,并检查 Pi 相关结果保留两位小数后是否符合样例。可以用 var _ Shape = Circle{} 与 var _ Shape = Rectangle{} 在编译期断言接口实现完整。
代码示例
package main
import "math"
type Shape interface {
Area() float64
Perimeter() float64
}
type Circle struct{ Radius float64 }
func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.Radius }
type Rectangle struct{ Width, Height float64 }
func (r Rectangle) Area() float64 { return r.Width * r.Height }
func (r Rectangle) Perimeter() float64 { return 2 * (r.Width + r.Height) }