面试题答案
一键面试package main
import (
"fmt"
)
// 定义Shape接口,包含Area方法
type Shape interface {
Area() float64
}
// Circle结构体
type Circle struct {
radius float64
}
// Circle实现Shape接口的Area方法
func (c Circle) Area() float64 {
return 3.14 * 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
}
func main() {
// 创建Circle和Rectangle实例
circle := Circle{radius: 5}
rectangle := Rectangle{width: 4, height: 6}
// 创建一个Shape类型的切片,里面包含Circle和Rectangle实例
shapes := []Shape{circle, rectangle}
// 遍历切片,通过接口调用Area方法计算不同图形的面积
for _, shape := range shapes {
fmt.Printf("The area of the shape is: %f\n", shape.Area())
}
}
在上述代码中:
- 首先定义了
Shape
接口,包含Area
方法。 - 然后分别定义了
Circle
和Rectangle
结构体,并为它们实现了Shape
接口的Area
方法。 - 在
main
函数中,创建了Circle
和Rectangle
的实例,并将它们放入一个Shape
类型的切片中。通过遍历这个切片,调用接口的Area
方法,实现了代码复用,计算不同图形的面积。