我正在通过阅读“Effective Go”来学习 Go 语言。
我找到了一个关于类型切换的例子:
var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T\n", t) // %T prints whatever type t has
case bool:
fmt.Printf("boolean %t\n", t) // t has type bool
case int:
fmt.Printf("integer %d\n", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}
我的理解是switch从上到下评估案例并在匹配条件下停止。那么这个例子不是总是停留在default并打印“意外类型......”吗?
猛跑小猪
相关分类