skip to content
Alvin Lucillo

Type assertion and type switch in Go

/ 1 min read

💻 Tech

In Go, an any variable can hold any types. any is an alias for interface{}. It’s a best practice not to use any unless absolute necessary. When receiving an any type (i.e., blank interface), you can perform a type assertion or type switch.

func main() {
	var x any // any is an alias for interface{}

	x = "hello"
	fmt.Println(x) // 12345

	x = 12345
	fmt.Println(x) // 12345

	// type assertion
	i := x.(int)
	fmt.Println(i) // 12345

	// type assertion with ok
	s, ok := x.(string)
	fmt.Printf("%v %v\n", s, ok) // empty string, false

	// x = make([]byte, 0) causes type switch to print: unsupported type: []uint8

	// type switch
	switch x.(type) { // found int
	case int:
		fmt.Println("found int")
	case string:
		fmt.Println("found string")
	default:
		fmt.Printf("unsupported type: %T\n", x)
	}
}