What is the use of Go's type switches for dynamic type checking?
Type switches are a construct in Go that allow you to test the type of an interface value. They are particularly useful in situations where you have an interface value, but you don't know its underlying type, and you need to perform different operations depending on the type.
Here's an example of how to use a type switch:
func process(i interface{}) {
switch v := i.(type) {
case int:
fmt.Println("Integer:", v)
case float64:
fmt.Println("Float:", v)
case string:
fmt.Println("String:", v)
default:
fmt.Println("Unknown type")
}
}
func main() {
process(42)
process(3.14)
process("hello")
process(true)
}
In this example, the **process**
function takes an interface value **i**
as an argument. The **switch**
statement then tests the underlying type of the value using the **.(type)**
syntax. Depending on the type of the value, the appropriate case is executed.
Note that the **default**
case is used to handle any types that are not explicitly handled in the **case**
statements.
Type switches are a powerful tool in Go that allow you to write flexible and concise code that can handle a wide variety of types. However, it's important to use them judiciously, as they can make code harder to read and maintain if overused.