Sobes.tech
Junior

What is a type switch in Go?

sobes.tech AI

Answer from AI

Type switch is a construct in Go, similar to a regular switch, but used to determine the actual type of an interface variable and execute the corresponding block of code depending on this type.

Syntax:

switch v := x.(type) {
// v has the same type as x in each case.
case T1:
	// actions for type T1
case T2:
	// actions for type T2
default:
	// actions for all other types
}

In this syntax:

  • x is an expression of interface type.
  • (type) is a keyword indicating that this is a type switch.
  • v := x.(type) is a short variable declaration that, in each case, binds the variable v to a copy of x converted to the type of the respective case. Note that unlike type assertion x.(T), which requires a specific type T, here the keyword type is used.
  • case T1, case T2, ... are blocks executed if the actual type of x matches the specified type T1, T2, etc.
  • default is an optional block executed if the actual type of x does not match any of the specified types in the case.

Type switch is useful when you need to handle the value of an interface differently depending on its underlying type.

Example usage:

func printType(v interface{}) {
	switch v.(type) {
	case int:
		fmt.Println("This is an integer")
	case string:
		fmt.Println("This is a string")
	case bool:
		fmt.Println("This is a boolean")
	default:
		fmt.Println("Unknown type")
	}
}

func main() {
	printType(10)
	printType("hello")
	printType(true)
	printType(3.14)
}

Output:

This is an integer
This is a string
This is a boolean
Unknown type

You can also use the variable declared in the switch header to access the value with the asserted type inside the case block:

func printValueByType(v interface{}) {
	switch value := v.(type) {
	case int:
		fmt.Printf("This is an integer: %d\n", value)
	case string:
		fmt.Printf("This is a string: %s\n", value)
	case bool:
		fmt.Printf("This is a boolean: %t\n", value)
	default:
		fmt.Println("Unknown type")
	}
}

func main() {
	printValueByType(100)
	printValueByType("world")
	printValueByType(false)
}

Output:

This is an integer: 100
This is a string: world
This is a boolean: false

Advantages of type switch over a chain of type assertions:

  • More readable code when handling multiple types.
  • More efficient (the compiler can optimize).
  • The variable declared in the switch header automatically has the correct type in each case.