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 协议》,转载必须注明作者和本文链接