-2
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:
    }
tanxin
  • 145
  • 10
  • 1
    That's an **expression** switch not a **type** switch, **do NOT feed types to expression switch cases**. `case string:` can be ok ONLY if you have overwritten the predeclared type identifier by declaring a variable with the same name. See https://go.dev/play/p/iVusyyiyhWK, `string` is NOT an expression (unless you've declared a variable with that name). – mkopriva Aug 10 '22 at 12:03

1 Answers1

1

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.

NotX
  • 1,516
  • 1
  • 14
  • 28
  • The prbolem is not i.(type) nor reflect.TypeOf(i), the problem is ```case []byte``` is not correct. I realy want to know how to deal with the case when type is ```[]byte``` – tanxin Aug 10 '22 at 11:44
  • 1
    @tanxin `[]byte` is not a possible implementation of the `Type` interface (that you get from `reflect.TypeOf()`). Neither is `string` (and my compiler complains about that one, too). – NotX Aug 10 '22 at 11:46
  • I edited my question by adding an example. – tanxin Aug 10 '22 at 12:04
  • Your example equals my one. It's a type switch, as suggested. The only difference is that your example reads `switch v.(type`) while mine was `switch i.(type)`, so it's basically just different naming. Additionally, your example isn't really related to your question. – NotX Aug 10 '22 at 12:09