MST

星途 面试题库

面试题:Go空接口集成第三方库的类型断言处理

假设你通过空接口集成了一个第三方的图形绘制库,该库返回的图形对象都被赋值给了空接口类型变量。现在你需要根据不同的图形类型(例如圆形、矩形)执行不同的绘制操作,你将如何使用类型断言和类型选择来实现这一功能?请编写相应的Go代码实现。
26.3万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "fmt"
)

// 定义图形接口
type Shape interface {
    Draw()
}

// 圆形结构体
type Circle struct {
    Radius float64
}

func (c Circle) Draw() {
    fmt.Printf("绘制圆形,半径: %f\n", c.Radius)
}

// 矩形结构体
type Rectangle struct {
    Width  float64
    Height float64
}

func (r Rectangle) Draw() {
    fmt.Printf("绘制矩形,宽: %f, 高: %f\n", r.Width, r.Height)
}

func main() {
    // 模拟第三方库返回的空接口类型变量
    var shapes []interface{}
    shapes = append(shapes, Circle{Radius: 5.0})
    shapes = append(shapes, Rectangle{Width: 4.0, Height: 3.0})

    // 使用类型断言和类型选择执行不同绘制操作
    for _, shape := range shapes {
        switch s := shape.(type) {
        case Circle:
            s.Draw()
        case Rectangle:
            s.Draw()
        default:
            fmt.Println("不支持的图形类型")
        }
    }
}