面试题答案
一键面试package main
import (
"fmt"
)
// 定义Shape接口
type Shape interface {
Area() float64
}
// 定义Circle结构体并实现Shape接口
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
// 定义Rectangle结构体并实现Shape接口
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// CalculateTotalArea函数计算所有形状的总面积
func CalculateTotalArea(shapes []Shape) float64 {
totalArea := 0.0
for _, shape := range shapes {
totalArea += shape.Area()
}
return totalArea
}
可以通过以下方式调用:
func main() {
circles := []Circle{
{Radius: 5},
{Radius: 3},
}
rectangles := []Rectangle{
{Width: 4, Height: 6},
{Width: 2, Height: 8},
}
var shapes []Shape
for _, c := range circles {
shapes = append(shapes, c)
}
for _, r := range rectangles {
shapes = append(shapes, r)
}
totalArea := CalculateTotalArea(shapes)
fmt.Printf("Total Area: %.2f\n", totalArea)
}
动态类型和静态类型分析
- 静态类型:
- 在Go语言中,接口类型
Shape
是静态类型。CalculateTotalArea
函数的参数shapes
是[]Shape
类型,这里Shape
就是静态类型。 - 声明变量时,如
var shapes []Shape
,shapes
的静态类型是[]Shape
。静态类型在编译时就确定了,它决定了变量可以调用哪些方法。在这个例子中,由于shapes
的静态类型是[]Shape
,所以可以调用Shape
接口定义的Area()
方法。
- 在Go语言中,接口类型
- 动态类型:
- 当将
Circle
或Rectangle
结构体实例添加到shapes
切片中时,这些实例的实际类型就是动态类型。例如,circles
中的Circle
实例和rectangles
中的Rectangle
实例,在作为Shape
类型的元素放入shapes
切片后,它们各自的Circle
和Rectangle
类型就是动态类型。 - 在
CalculateTotalArea
函数中,通过shape.Area()
调用方法时,Go语言会根据shape
的动态类型来决定实际调用哪个类型的Area
方法。如果shape
的动态类型是Circle
,就调用Circle
的Area
方法;如果是Rectangle
,就调用Rectangle
的Area
方法。这就是Go语言实现多态的方式,通过接口的动态类型在运行时确定实际调用的方法。
- 当将