How to Use Type Switches in Go

Use a type switch to run specific code blocks based on the dynamic type of an interface value.

Use a type switch to execute different code blocks based on the dynamic type of an interface value by matching against specific types in the case clauses. The variable declared in the switch statement takes the type of the matched case within that block.

func describe(i interface{}) {
	switch v := i.(type) {
	case int:
		fmt.Printf("twice %v is %v\n", v, v*2)
	case string:
		fmt.Printf("%q is %d bytes long\n", v, len(v))
	default:
		fmt.Printf("unsupported type: %T\n", v)
	}
}