面试题答案
一键面试常见应用场景
- 处理不同类型的具体实现:当一个接口有多种不同类型的实现时,通过类型断言可以针对不同的具体类型进行特定的处理。例如在图形绘制的接口,不同图形(圆形、矩形等)实现该接口,通过类型断言对不同图形进行特定绘制操作。
- 在通用容器中提取特定类型数据:如果有一个通用的容器(如接口类型的切片)存储了不同类型的数据,需要对其中某一类型的数据进行操作时,可使用类型断言。
示例代码
package main
import (
"fmt"
)
// 定义一个接口
type Shape interface {
Area() float64
}
// 定义圆形结构体并实现Shape接口
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
// 定义矩形结构体并实现Shape接口
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func main() {
// 创建一个接口类型的切片,包含不同类型的形状
shapes := []Shape{
Circle{Radius: 5},
Rectangle{Width: 4, Height: 6},
}
for _, shape := range shapes {
// 使用类型断言进行特定类型的操作
if circle, ok := shape.(Circle); ok {
fmt.Printf("Circle area: %.2f\n", circle.Area())
} else if rectangle, ok := shape.(Rectangle); ok {
fmt.Printf("Rectangle area: %.2f\n", rectangle.Area())
}
}
}
在上述代码中,Shape
接口有 Circle
和 Rectangle
两种不同类型的实现。通过在 main
函数中遍历 Shape
接口类型的切片,使用类型断言判断具体的类型,并进行相应类型的操作。