func Test(val any) {
switch reflect.TypeOf(val) {
case nil://ok
case string://ok
case []byte://error here,expected expression
}
}
As the code above, I am trying to make some statement according to the type of input value. However it fails to pass the grammer check when the type of input value is []byte. How to fix this
problem?
I found an example and I think is what I need:
switch v.(type) {
case *string:
case *[]byte:
case *int:
case *bool:
case *float32:
case *[]string:
case *map[string]string:
case *map[string]interface{}:
case *time.Duration:
case *time.Time:
}
reflect.TypeOf()returns an object of the interfaceType, which isn't implemented by[]byte(orstring).You can go that route to switch betwen types (taken from https://go.dev/tour/methods/16):
If you don't need
v,switch i.(type)is also fine.