英文:
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)
}
}
如果你不需要 v
,switch 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论