Go 接口进阶
类型断言、类型 switch、空接口 any · 难度:高级 · +20XP
接口进阶操作
类型断言
从接口值中提取具体类型:
var i interface{} = "hello"
s, ok := i.(string) // ok=true, s="hello"
n, ok := i.(int) // ok=false, n=0(断言失败不 panic)
类型 Switch
func describe(i interface{}) {
switch v := i.(type) {
case string: fmt.Printf("string: %s (len=%d)
", v, len(v))
case int: fmt.Printf("int: %d
", v)
case []int: fmt.Printf("[]int: len=%d
", len(v))
default: fmt.Printf("unknown type: %T
", v)
}
}
空接口 interface{} / any
Go 1.18+ 引入了 any 作为 interface{} 的别名。可以接收任意类型,类似于其他语言的 Object。
var x any = 42
x = "hello"
x = []int{1, 2, 3}
// 使用前必须类型断言