Junior — Middle
What is the use of the type switch construct in programming languages?
sobes.tech AI
Answer from AI
The type switch construct in Go is used to determine the actual type of a value in an interface at runtime. This allows executing different actions depending on the type of the variable that implements the interface.
Example usage:
var i interface{} = 10
switch v := i.(type) {
case int:
fmt.Println("int", v)
case string:
fmt.Println("string", v)
default:
fmt.Println("unknown type")
}
Here, i.(type) allows checking what specific type is stored in the interface i, and executing the corresponding block of code.