switch还可以用于判断变量类型。使用方式为T.(type),即在变量后加上.(type)。见代码:
package main
import (
"fmt"
)
func main() {
var a interface{}
a = "abc"
switch t := a.(type) {
case string:
fmt.Printf("string %s\n", t)
case int:
fmt.Printf("int %d\n", t)
default:
fmt.Printf("unexpected type %T", t)
}
}
输出结果为:
string abc
如果将上面的:
var a interface{}
a = "abc"
这两句,合成一句:
a := "abc"
编译就会出错:
cannot type switch on non-interface value a (type string)
不能在一个非接口类型的变量上使用type switch。
也就是说 type switch只能用于接口的变量。
来源:https://www.cnblogs.com/baiyuxiong/p/4320963.html