fix conv
This commit is contained in:
58
conv/conv.go
58
conv/conv.go
@@ -1,19 +1,67 @@
|
||||
package conv
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// AnyToString 任意类型转字符串
|
||||
// in: 输入值
|
||||
// 返回: 转换后的字符串
|
||||
func AnyToString(in any) (s string) {
|
||||
// AnyToString 将任意值转为可读的字符串:nil 为空串;标量与 []byte 用 strconv;指针会解引用;其余走 fmt.Sprint。
|
||||
func AnyToString(in any) string {
|
||||
for in != nil {
|
||||
rv := reflect.ValueOf(in)
|
||||
if rv.Kind() != reflect.Ptr {
|
||||
break
|
||||
}
|
||||
if rv.IsNil() {
|
||||
return ""
|
||||
}
|
||||
in = rv.Elem().Interface()
|
||||
}
|
||||
if in == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return in.(string)
|
||||
switch v := in.(type) {
|
||||
case string:
|
||||
return v
|
||||
case []byte:
|
||||
return string(v)
|
||||
case bool:
|
||||
return strconv.FormatBool(v)
|
||||
case int:
|
||||
return strconv.Itoa(v)
|
||||
case int8:
|
||||
return strconv.FormatInt(int64(v), 10)
|
||||
case int16:
|
||||
return strconv.FormatInt(int64(v), 10)
|
||||
case int32:
|
||||
return strconv.FormatInt(int64(v), 10)
|
||||
case int64:
|
||||
return strconv.FormatInt(v, 10)
|
||||
case uint:
|
||||
return strconv.FormatUint(uint64(v), 10)
|
||||
case uint8:
|
||||
return strconv.FormatUint(uint64(v), 10)
|
||||
case uint16:
|
||||
return strconv.FormatUint(uint64(v), 10)
|
||||
case uint32:
|
||||
return strconv.FormatUint(uint64(v), 10)
|
||||
case uint64:
|
||||
return strconv.FormatUint(v, 10)
|
||||
case float32:
|
||||
return strconv.FormatFloat(float64(v), 'f', -1, 32)
|
||||
case float64:
|
||||
return strconv.FormatFloat(v, 'f', -1, 64)
|
||||
case json.Number:
|
||||
return string(v)
|
||||
default:
|
||||
if s, ok := in.(fmt.Stringer); ok {
|
||||
return s.String()
|
||||
}
|
||||
return fmt.Sprint(in)
|
||||
}
|
||||
}
|
||||
|
||||
// AnyToInt 将动态类型转为 int(两仓库 internal 中逻辑一致,此处合并分支)。
|
||||
|
||||
Reference in New Issue
Block a user