what’s type switch in Go
tags: learning go programming
content
- in go-type-assertion-1, we have code like:
var x any
x := 10
value, ok := x.(int)
if ok {
fmt.Println(value, "is an int")
}- if we wanna do different stuff based on the type, we can use a switch statement:
func checkType(i any) {
switch value := i.(type)
case int:
fmt.Println(value, "is an int")
case string:
fmt.Println(value, "is a string")
default:
fmt.Println("unknown type")
}