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

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

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

问题

func Test(val any) {
    switch reflect.TypeOf(val).Elem().Kind() {
    case reflect.Slice:
        switch reflect.TypeOf(val).Elem().Elem().Kind() {
        case reflect.Uint8:
            // handle []byte case
        }
    }
}

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

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

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

以上是修复问题的方法。

英文:
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

得分: 1

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

你可以使用以下方法在不同类型之间进行切换(取自 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)
	}
}

如果你不需要 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):

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.

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:

确定