Type switches

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.

  1. switch v := i.(type) {
  2. case T:
  3. // here v has type T
  4. case S:
  5. // here v has type S
  6. default:
  7. // no match; here v has the same type as i
  8. }

The declaration in a type switch has the same syntax as a type assertion i.(T), but the specific type T is replaced with the keyword type.

This switch statement tests whether the interface value i holds a value of type T or S. In each of the T and S cases, the variable v will be of type T or S respectively and hold the value held by i. In the default case (where there is no match), the variable v is of the same interface type and value as i.

type-switches.go

  1. package main
  2. import "fmt"
  3. func do(i interface{}) {
  4. switch v := i.(type) {
  5. case int:
  6. fmt.Printf("Twice %v is %v\n", v, v*2)
  7. case string:
  8. fmt.Printf("%q is %v bytes long\n", v, len(v))
  9. default:
  10. fmt.Printf("I don't know about type %T!\n", v)
  11. }
  12. }
  13. func main() {
  14. do(21)
  15. do("hello")
  16. do(true)
  17. }