当类型为[]byte时,在Golang的case语句中失败。

huangapple go评论105阅读模式
英文:

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

问题

  1. func Test(val any) {
  2. switch reflect.TypeOf(val).Elem().Kind() {
  3. case reflect.Slice:
  4. switch reflect.TypeOf(val).Elem().Elem().Kind() {
  5. case reflect.Uint8:
  6. // handle []byte case
  7. }
  8. }
  9. }

在上面的代码中,我试图根据输入值的类型进行一些语句处理。然而,当输入值的类型为[]byte时,它无法通过语法检查。如何解决这个问题?

我找到了一个示例,我认为这就是我需要的:

  1. switch v.(type) {
  2. case *string:
  3. case *[]byte:
  4. case *int:
  5. case *bool:
  6. case *float32:
  7. case *[]string:
  8. case *map[string]string:
  9. case *map[string]interface{}:
  10. case *time.Duration:
  11. case *time.Time:
  12. }

以上是修复问题的方法。

英文:
  1. func Test(val any) {
  2. switch reflect.TypeOf(val) {
  3. case nil://ok
  4. case string://ok
  5. case []byte://error here,expected expression
  6. }
  7. }

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:

  1. switch v.(type) {
  2. case *string:
  3. case *[]byte:
  4. case *int:
  5. case *bool:
  6. case *float32:
  7. case *[]string:
  8. case *map[string]string:
  9. case *map[string]interface{}:
  10. case *time.Duration:
  11. case *time.Time:
  12. }

答案1

得分: 1

reflect.TypeOf() 返回一个 Type 接口的对象,[]byte(或 string)并没有实现该接口。

你可以使用以下方法在不同类型之间进行切换(取自 https://go.dev/tour/methods/16):

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

如果你不需要 vswitch i.(type) 也可以。

英文:

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):

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

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

huangapple
  • 本文由 发表于 2022年8月10日 19:21:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/73305399.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定