MST

星途 面试题库

面试题:Go中struct方法与接口的深度结合应用

定义一个接口 `Shape` 包含 `Area` 方法用于计算面积。然后定义两个结构体 `Circle` 和 `Rectangle`,分别为它们实现 `Shape` 接口的 `Area` 方法。接着,定义一个函数 `CalculateTotalArea`,它接受一个 `Shape` 接口类型的切片作为参数,计算并返回所有形状的总面积。同时说明在这个过程中struct方法是如何与接口进行交互和实现多态的。
11.2万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
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 方法通过实现接口中定义的方法来与接口进行交互。当 CircleRectangle 结构体分别实现了 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)
}