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("不支持的图形类型")
}
}
}