MST

星途 面试题库

面试题:Go中接口方法调用的边界控制 - 基础实现

请编写一段Go代码,定义一个接口`Shape`,包含`Area`方法。再定义`Circle`和`Rectangle`结构体实现该接口。在主函数中创建一个`Shape`类型的切片,将`Circle`和`Rectangle`的实例放入切片,通过遍历切片调用`Area`方法。同时,说明如何在这个过程中进行简单的边界控制,例如确保面积计算的参数合理。
17.1万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
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。这样确保了面积计算的参数合理。