Type switch in Go

A type switch in Go checks the dynamic type of an interface value and executes specific code blocks for each matched type.

A type switch in Go checks the dynamic type of an interface value and executes code specific to that type. Use the switch statement with the interface variable, then list case clauses for each concrete type you want to handle, optionally extracting the value into a typed variable.

func describe(i interface{}) {
	switch v := i.(type) {
	case int:
		fmt.Printf("int %d\n", v)
	case string:
		fmt.Printf("string %q\n", v)
	case bool:
		fmt.Printf("bool %t\n", v)
	default:
		fmt.Printf("unknown type %T\n", v)
	}
}