How is it possible to use a switch type on the value of reflect.TypeOf(value)
import (
"fmt"
"reflect"
)
func main() {
var value int = 123
t := reflect.TypeOf(value)
switch tv := t.(type) {
case int:
fmt.Println("type: INT")
}
fmt.Println(t)
}
t
's type is the reflect.Type
interface type, and the concrete type stored in it is always the unexported *reflect.rtype
pointer type descriptor, so there's no sense type-switching on that.
Use a switch
statement and compare to other reflect.Type
values like this:
for _, v := range []any{
int(123), "foo", float64(1.0),
} {
t := reflect.TypeOf(v)
switch t {
case reflect.TypeOf(int(0)):
fmt.Println("type: INT")
case reflect.TypeOf(""):
fmt.Println("type: STRING")
default:
fmt.Println("type: other:", t)
}
}
This will output (try it on the Go Playground):
type: INT
type: STRING
type: other: float64
If you have to run this many times, you can cache the type descriptors you're interested in:
var (
typeInt = reflect.TypeOf(int(0))
typeString = reflect.TypeOf("")
)
Then the switch
:
switch t {
case typeInt:
fmt.Println("type: INT")
case typeString:
fmt.Println("type: STRING")
default:
fmt.Println("type: other:", t)
}
This outputs the same. Try this one on the Go Playground.