A type switch compares types rather than values. It is otherwise similar to an expression switch. It is marked by a special switch expression that has the form of a type assertion using the reserved word type
rather than an actual type:
switch x.(type) { // cases }Cases then match actual types
T
against the dynamic type of the expression
x
. As with type assertions,
x
must be of
interface type
, and each non-interface type
T
listed in a case must implement the type of
x
. The types listed in the cases of a type switch must all be
different
.
The type in a case may be nil
; that case is used when x is a nil
interface value. There may be at most one nil
case.
Given an expression x
of type interface{}
, the following type switch:
switch i := x.(type) { case nil: printString("x is nil") // type of i is type of x (interface{}) case int: printInt(i) // type of i is int case float64: printFloat64(i) // type of i is float64 case func(int) float64: printFunction(i) // type of i is func(int) float64 case bool, string: printString("type is bool or string") // type of i is type of x (interface{}) default: printString("don't know the type") // type of i is type of x (interface{}) }could be rewritten:
v := x // x is evaluated exactly once if v == nil { i := v // type of i is type of x (interface{}) printString("x is nil") } else if i, isInt := v.(int); isInt { printInt(i) // type of i is int } else if i, isFloat64 := v.(float64); isFloat64 { printFloat64(i) // type of i is float64 } else if i, isFunc := v.(func(int) float64); isFunc { printFunction(i) // type of i is func(int) float64 } else { _, isBool := v.(bool) _, isString := v.(string) if isBool || isString { i := v // type of i is type of x (interface{}) printString("type is bool or string") } else { i := v // type of i is type of x (interface{}) printString("don't know the type") } }注意:T he "fallthrough" statement is not permitted in a type switch.