面试题答案
一键面试package main
import (
"fmt"
"math"
)
// 定义Shape接口
type Shape interface {
Area() float64
}
// 定义Circle结构体
type Circle struct {
Radius float64
}
// Circle实现Shape接口的Area方法
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
// 定义Rectangle结构体
type Rectangle struct {
Width float64
Height float64
}
// Rectangle实现Shape接口的Area方法
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// CalculateTotalArea函数计算所有形状的总面积
func CalculateTotalArea(shapes []Shape) float64 {
var totalArea float64
for _, shape := range shapes {
totalArea += shape.Area()
}
return totalArea
}
在这个过程中,struct
方法通过实现接口中定义的方法来与接口进行交互。当 Circle
和 Rectangle
结构体分别实现了 Shape
接口的 Area
方法后,它们就可以被当作 Shape
类型来使用。在 CalculateTotalArea
函数中,接受 Shape
接口类型的切片,这使得该函数可以接受任何实现了 Shape
接口的结构体实例,而无需关心具体的结构体类型。这就是Go语言中实现多态的方式,通过接口来抽象行为,不同的结构体通过实现接口方法来表现出不同的行为。
在使用时可以这样调用:
func main() {
circle := Circle{Radius: 5}
rectangle := Rectangle{Width: 4, Height: 6}
shapes := []Shape{circle, rectangle}
totalArea := CalculateTotalArea(shapes)
fmt.Printf("Total Area: %.2f\n", totalArea)
}