登录
首页 >  Golang >  Go问答

golang中使用byte类型时的case语句问题

来源:stackoverflow

时间:2024-02-11 12:00:25 236浏览 收藏

本篇文章向大家介绍《golang中使用byte类型时的case语句问题》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

func test(val any) {
    switch reflect.typeof(val) {
    case nil://ok
    case string://ok
    case []byte://error here,expected expression
    }
}

如上面的代码,我试图根据输入值的类型做出一些声明。然而,当输入值的类型为 []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:
    }

正确答案


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) 也可以。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>