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:
xis 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 eachcase, binds the variablevto a copy ofxconverted to the type of the respectivecase. Note that unlike type assertionx.(T), which requires a specific typeT, here the keywordtypeis used.case T1, case T2, ...are blocks executed if the actual type ofxmatches the specified typeT1,T2, etc.defaultis an optional block executed if the actual type ofxdoes not match any of the specified types in thecase.
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.