面试题答案
一键面试package main
import (
"fmt"
"math"
)
// 定义Shape接口
type Shape interface {
Area() float64
}
// 定义Rectangle结构体并实现Shape接口
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// 定义Circle结构体并实现Shape接口
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
func main() {
var shapes []interface{}
shapes = append(shapes, Rectangle{Width: 5, Height: 10})
shapes = append(shapes, Circle{Radius: 3})
totalArea := 0.0
for _, shape := range shapes {
if rect, ok := shape.(Rectangle); ok {
totalArea += rect.Area()
} else if circ, ok := shape.(Circle); ok {
totalArea += circ.Area()
}
}
fmt.Printf("所有图形的总面积: %.2f\n", totalArea)
}
上述代码定义了Shape
接口,以及Rectangle
和Circle
结构体并实现了Shape
接口。在main
函数中,创建了一个[]interface{}
类型的切片,并添加了Rectangle
和Circle
的实例。通过类型断言判断每个元素的实际类型,并计算所有图形的总面积。