MST

星途 面试题库

面试题:Go语言接口类型转换与断言在复杂结构中的应用

定义一个接口 `Shape`,包含 `Area` 方法用于计算面积。再定义 `Rectangle` 和 `Circle` 结构体并实现 `Shape` 接口。现有一个 `[]interface{}` 类型的切片,其中存放了若干 `Rectangle` 和 `Circle` 结构体实例。请编写代码遍历该切片,使用类型断言判断每个元素的实际类型,并计算所有图形的总面积。
44.6万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "fmt"
    "math"
)

// 定义Shape接口
type Shape interface {
    Area() float64
}

// 定义Rectangle结构体并实现Shape接口
type Rectangle struct {
    Width  float64
    Height float64
}

func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

// 定义Circle结构体并实现Shape接口
type Circle struct {
    Radius float64
}

func (c Circle) Area() float64 {
    return math.Pi * c.Radius * c.Radius
}

func main() {
    var shapes []interface{}
    shapes = append(shapes, Rectangle{Width: 5, Height: 10})
    shapes = append(shapes, Circle{Radius: 3})

    totalArea := 0.0
    for _, shape := range shapes {
        if rect, ok := shape.(Rectangle); ok {
            totalArea += rect.Area()
        } else if circ, ok := shape.(Circle); ok {
            totalArea += circ.Area()
        }
    }

    fmt.Printf("所有图形的总面积: %.2f\n", totalArea)
}

上述代码定义了Shape接口,以及RectangleCircle结构体并实现了Shape接口。在main函数中,创建了一个[]interface{}类型的切片,并添加了RectangleCircle的实例。通过类型断言判断每个元素的实际类型,并计算所有图形的总面积。