主题
空接口与类型断言
1. 空接口(interface{})
空接口没有任何方法,所有类型都实现了空接口,因此空接口可以存储任意类型的值。
go
var x interface{}
x = 42
x = "hello"
x = struct{ Name string }{Name: "Go"}
2. 类型断言
从接口变量中提取具体类型的值,使用类型断言:
go
var x interface{} = "hello"
s, ok := x.(string)
if ok {
fmt.Println("字符串值:", s)
} else {
fmt.Println("不是字符串")
}
断言失败时,ok
为 false
,防止运行时错误。
3. 类型开关
使用 switch
语句对接口类型进行多路判断:
go
switch v := x.(type) {
case int:
fmt.Println("整数", v)
case string:
fmt.Println("字符串", v)
default:
fmt.Println("其他类型")
}
空接口和类型断言支持动态类型处理,是 Go 语言灵活性的关键。