Junior — Middle
Explain the working principle of the type switch construct in the Go language and how it differs from a regular switch-case.
sobes.tech AI
Answer from AI
In the Go language, the type switch construct is used to determine the specific type of an interface value at runtime. It allows performing different actions depending on the type to which the variable implementing the interface belongs.
Example syntax:
switch v := x.(type) {
case int:
fmt.Println("int", v)
case string:
fmt.Println("string", v)
default:
fmt.Println("other type")
}
Here, x is a variable of interface type, and v is a variable with a specific type within each case.
Difference from a regular switch-case:
- A regular switch compares the value of an expression with constants or expressions.
- A type switch compares the type of the interface value, not the value itself.
Type switch is useful for working with interfaces when you need to perform different actions depending on the actual type of the object stored in the interface.