接口变量的类型也可以使用一种特殊形式的type switch语法,即 i.(T) 进行检测。

A type switch is a construct that permits several type assertions in series.

A type switch is like a regular switch statement, but the cases in a type switch specify types (not values), and those values are compared against the type of the value held by the given interface value.

即:
类型转换是一种允许串联多个类型断言的结构。

类型转换就像普通的switch开关语句,但类型转换中的情况指定的是类型(而不是值),这些值将与给定接口值所持有的值的类型进行比较。

例如:

package main

import "fmt"

func do(i interface{}) {
	switch v := i.(type) {
	case int:
		fmt.Printf("Twice %v is %v\n", v, v*2)
	case string:
		fmt.Printf("%q is %v bytes long\n", v, len(v))
	default:
		fmt.Printf("I don't know about type %T!\n", v)
	}
}

func main() {
	do(21)
	do("hello")
	do(true)
}
//输出:
Twice 21 is 42
"hello" is 5 bytes long
I don't know about type bool!

注意: golang 中类型断言Type assertions也是使用。i.(T) 的语法,但类型断言中 T 为特定的类型,而Type switches中特定的类型T被关键字type替换。