优化类型的定义

This commit is contained in:
Yun
2024-10-28 20:02:37 +08:00
parent 832e70ba48
commit 1e41151c1d
6 changed files with 232 additions and 102 deletions
+34 -32
View File
@@ -2,43 +2,45 @@ package convx
import (
"errors"
"fmt"
"strconv"
)
// interface 转 string
func ToString(val interface{}) (str string, err error) {
var s string
if vv, ok := val.(float32); ok {
s = strconv.FormatFloat(float64(vv), 'f', -1, 32)
} else if vv, ok := val.(float64); ok {
s = strconv.FormatFloat(vv, 'f', -1, 64)
} else if vv, ok := val.(int); ok {
s = strconv.Itoa(vv)
} else if vv, ok := val.(int32); ok {
s = strconv.Itoa(int(vv))
} else if vv, ok := val.(int64); ok {
s = strconv.FormatInt(vv, 10)
} else if vv, ok := val.(string); ok {
s = vv
} else if vv, ok := val.(bool); ok {
s = strconv.FormatBool(vv)
} else if vv, ok := val.(uint); ok {
s = strconv.FormatUint(uint64(vv), 10)
} else if vv, ok := val.(uint32); ok {
s = strconv.FormatUint(uint64(vv), 10)
} else if vv, ok := val.(uint64); ok {
s = strconv.FormatUint(vv, 10)
} else if vv, ok := val.(uint8); ok {
s = strconv.FormatUint(uint64(vv), 10)
} else if vv, ok := val.(uint16); ok {
s = strconv.FormatUint(uint64(vv), 10)
} else if vv, ok := val.(int8); ok {
s = strconv.FormatInt(int64(vv), 10)
} else if vv, ok := val.(int16); ok {
s = strconv.FormatInt(int64(vv), 10)
} else {
return s, errors.New("不支持的参数类型")
switch v := val.(type) {
case nil:
return "", fmt.Errorf("can not convert to string")
case string:
return v, nil
case int:
return strconv.Itoa(v), nil
case int8:
return strconv.FormatInt(int64(v), 10), nil
case int16:
return strconv.FormatInt(int64(v), 10), nil
case int32:
return strconv.FormatInt(int64(v), 10), nil
case int64:
return strconv.FormatInt(v, 10), nil
case float32:
return strconv.FormatFloat(float64(v), 'f', -1, 32), nil
case float64:
return strconv.FormatFloat(v, 'f', -1, 64), nil
case bool:
return strconv.FormatBool(v), nil
case uint:
return strconv.FormatUint(uint64(v), 10), nil
case uint8:
return strconv.FormatUint(uint64(v), 10), nil
case uint16:
return strconv.FormatUint(uint64(v), 10), nil
case uint32:
return strconv.FormatUint(uint64(v), 10), nil
case uint64:
return strconv.FormatUint(v, 10), nil
}
return s, nil
return "", errors.New("can not convert to string")
}