面试题答案
一键面试package main
import (
"fmt"
"math"
)
// Shape 接口定义
type Shape interface {
Area() float64
}
// Circle 结构体实现 Shape 接口
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
if c.Radius <= 0 {
fmt.Println("半径不能小于等于0,使用默认值1")
c.Radius = 1
}
return math.Pi * c.Radius * c.Radius
}
// Rectangle 结构体实现 Shape 接口
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
if r.Width <= 0 {
fmt.Println("宽度不能小于等于0,使用默认值1")
r.Width = 1
}
if r.Height <= 0 {
fmt.Println("高度不能小于等于0,使用默认值1")
r.Height = 1
}
return r.Width * r.Height
}
func main() {
shapes := make([]Shape, 0)
circle := Circle{Radius: 5}
rectangle := Rectangle{Width: 4, Height: 6}
shapes = append(shapes, circle, rectangle)
for _, shape := range shapes {
fmt.Printf("面积: %f\n", shape.Area())
}
}
在这个代码中,对于 Circle
结构体,在 Area
方法里对半径进行了边界控制,如果半径小于等于0,则使用默认值1。对于 Rectangle
结构体,在 Area
方法里对宽度和高度分别进行了边界控制,如果宽度或高度小于等于0,则分别使用默认值1。这样确保了面积计算的参数合理。