常见应用场景
- 获取具体类型的值:当我们有一个接口类型的变量,但实际需要访问其底层具体类型的值及其特有的方法时,可使用类型断言。比如在一个图形绘制的接口实现中,不同的图形(圆形、矩形等)实现了同一个绘制接口,当我们想对某个特定图形做额外操作时,可通过类型断言获取具体图形类型。
- 错误处理:在一些函数返回接口类型值,同时可能返回错误的场景下,通过类型断言来判断错误的具体类型,从而进行针对性处理。
代码示例
package main
import (
"fmt"
)
// 定义一个接口
type Shape interface {
Area() float64
}
// 圆形结构体
type Circle struct {
Radius float64
}
// 圆形的面积计算方法
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
// 矩形结构体
type Rectangle struct {
Width float64
Height float64
}
// 矩形的面积计算方法
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func main() {
// 创建一个Shape类型的切片,包含不同形状
shapes := []Shape{
Circle{Radius: 5},
Rectangle{Width: 4, Height: 6},
}
for _, shape := range shapes {
// 使用类型断言获取具体类型
if circle, ok := shape.(Circle); ok {
fmt.Printf("This is a circle with radius %f, area %f\n", circle.Radius, circle.Area())
} else if rectangle, ok := shape.(Rectangle); ok {
fmt.Printf("This is a rectangle with width %f and height %f, area %f\n", rectangle.Width, rectangle.Height, rectangle.Area())
}
}
}