面试题答案
一键面试实现思路
- 定义
Area
接口,包含GetArea
方法。 - 定义不同形状的结构体,如
Rectangle
和Circle
,并为它们实现Area
接口的GetArea
方法。 - 编写接收
[]interface{}
切片的函数,遍历切片,通过类型断言判断每个元素是否实现了Area
接口,如果实现了,则调用GetArea
方法并累加面积。
关键步骤
- 定义接口:
type Area interface {
GetArea() float64
}
- 定义形状结构体及实现接口:
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) GetArea() float64 {
return r.Width * r.Height
}
type Circle struct {
Radius float64
}
func (c Circle) GetArea() float64 {
return 3.14 * c.Radius * c.Radius
}
- 编写计算总面积的函数:
func CalculateTotalArea(shapes []interface{}) float64 {
totalArea := 0.0
for _, shape := range shapes {
if areaShape, ok := shape.(Area); ok {
totalArea += areaShape.GetArea()
}
}
return totalArea
}
示例使用
func main() {
shapes := []interface{}{
Rectangle{Width: 5, Height: 10},
Circle{Radius: 3},
}
total := CalculateTotalArea(shapes)
println(total)
}
以上代码通过定义接口、形状结构体实现接口,以及利用类型断言和接口多态性来计算切片中所有形状的总面积。