经常会用到传参用interface类型,接收使用的时候用来格式化字符串的时候无法直接格式化,做个转换工具函数:
顺带附一个常用的 可变参数类型,解决go的函数不带默认值问题以及参数过多问题
interface转换成字符串
//转换interface到字符串
func FmtStrFromInterface(val interface{}) string {
if val == nil {
return ""
}
switch ret := val.(type) {
case string:
return ret
case int8, uint8, int16, uint16, int, uint, int64, uint64, float32, float64:
return fmt.Sprintf("%v", ret)
}
return ""
}
type ParamMap struct {
param map[string]interface{}
}
func (pm *ParamMap) Len() int {
return len(pm.param)
}
func (pm *ParamMap) Set(key string, val interface{}) {
if pm.param == nil {
pm.param = make(map[string]interface{})
}
pm.param[key] = val
}
func (pm *ParamMap) Get(key string) interface{} {
return pm.param[key]
}
func (pm *ParamMap) GetStr(key string) string {
return common.FmtStrFromInterface(pm.param[key])
}
func (pm *ParamMap) GetInt(key string) int {
val := pm.param[key]
if val == nil {
return 0
}
switch ret := val.(type) {
case string:
number, _ := strconv.Atoi(ret)
return number
case int:
return ret
case float32:
return int(ret)
case float64:
return int(ret)
case uint32:
return int(ret)
case int64:
return int(ret)
case uint64:
return int(ret)
case int16:
return int(ret)
}
return 0
}
每个用这个类型传参的函数,可以在函数内部获取的时候根据需求实现默认参数的赋值