Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

type switch

  • interface

  • type

  • A variable defined as an interface can get any type

  • A switch statement can switch on the type of the variable

package main

import (
	"fmt"
)

func main() {
	var x interface{}
	x = 1
	//x = "other"
	//x = 3.14
	switch x.(type) {
	case int:
		fmt.Println("int")
	case float64:
		fmt.Println("float64")
	default:
		fmt.Println("other")
	}

}
  • multiple values in the same case
  • tagless switch statement with real comparisions like x < 23 in the cases, here cases can overlap
  • video
  • fallthrough
  • type switch