When type is []byte, it fails at case statement in golang

352 Views Asked by At
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:
    }
1

There are 1 best solutions below

4
NotX On

reflect.TypeOf() returns an object of the interface Type, which isn't implemented by []byte (or string).

You can go that route to switch betwen types (taken from https://go.dev/tour/methods/16):

func do(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Printf("Twice %v is %v\n", v, v*2)
    case string:
        fmt.Printf("%q is %v bytes long\n", v, len(v))
    default:
        fmt.Printf("I don't know about type %T!\n", v)
    }
}

If you don't need v, switch i.(type) is also fine.