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只能用於接口的變量。