interface{} 类型的转换

需求 类型是 interface{} , 值是 string , 但是需要转为 int64 , 转个类型费那么多功夫

每个类型都需要符合才行, 不能随便转

paramId := mapstr.MapStr{}\
paramId.Set("id", value3)\
id, err := paramId.Int64("id")

type MapStr map[string]interface{}
// Set set a new value for the key, the old value will be replaced\
func (cli MapStr) Set(key string, value interface{}) {\
   cli[key] = value\
}

func (cli MapStr) Int64(key string) (int64, error) {
    switch t := cli[key].(type) {
    default:
        return 0, errors.New("invalid num")
    case nil:
        return 0, errors.New("invalid key(" + key + "), not found value")
    case int:
        return int64(t), nil
    case int16:
        return int64(t), nil
    case int32:
        return int64(t), nil
    case int64:
        return t, nil
    case float32:
        return int64(t), nil
    case float64:
        return int64(t), nil
    case uint:
        return int64(t), nil
    case uint16:
        return int64(t), nil
    case uint32:
        return int64(t), nil
    case uint64:
        return int64(t), nil
    case json.Number:
        num, err := t.Int64()
        return int64(num), err
    case string:
        return strconv.ParseInt(t, 10, 64)
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
77
粉丝
8
喜欢
43
收藏
49
排名:84
访问:10.4 万
私信
所有博文
社区赞助商