Go 语言的 Type Switch 语句解析
讲述了Go语言中 Type Swith 的用法以及获取对应变量的一些特殊情况。 Type Switch 的基本用法 Type Switch 是 Go 语言中一种特殊的 switch 语句,它比较的是类型而不是具体的值。它判断某个接口变量的类型,然后根据具体类型再做相应处理。注意,在 Type Switch 语句的 case 子句中不能使用 fallthrough 。 它的用法如下。 switch x.( type ) { case Type1: doSomeThingWithType1() case Type2: doSomeThingWithType2() default : doSomeDefaultThing() } 其中, x 必须是一个接口类型的变量,而所有的 case 语句后面跟的类型必须实现了 x 的接口类型。 为了便于理解,我们可以结合下面这个例子来看: package main import ( "fmt" "reflect" ) type Animal interface { shout() string } type Dog struct {} func (self Dog) shout() string { return fmt.Sprintf( "wang wang" ) } type Cat struct {} func (self Cat) shout