go任意类型转字符串

直接上代码

 

复制代码
// 获取变量的字符串值
// 浮点型 3.0将会转换成字符串3, "3"
// 非数值或字符类型的变量将会被转换成JSON格式字符串
func Strval(value interface{}) string {
    var key string
    if value == nil {
        return key
    }

    switch value := value.(type) {
    case string:
        key = value

    case float64:
        key = strconv.FormatFloat(value, 'f', -1, 64)

    case float32:
        key = strconv.FormatFloat(float64(value), 'f', -1, 64)

    case int:
        key = strconv.Itoa(value)

    case int8:
        key = strconv.FormatInt(int64(value), 10)

    case int16:
        key = strconv.FormatInt(int64(value), 10)

    case int32:
        key = strconv.FormatInt(int64(value), 10)

    case int64:
        key = strconv.FormatInt(value, 10)

    case uint:
        key = strconv.FormatUint(uint64(value), 10)

    case uint8:
        key = strconv.FormatUint(uint64(value), 10)

    case uint16:
        key = strconv.FormatUint(uint64(value), 10)

    case uint32:
        key = strconv.FormatUint(uint64(value), 10)

    case uint64:
        key = strconv.FormatUint(value, 10)

    case []byte:
        key = string(value)

    default:
        newValue, _ := json.Marshal(value)
        key = string(newValue)
    }

    return key
}
复制代码

 

posted @   wsh3166Sir  阅读(103)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示