优化any转string

This commit is contained in:
Yun
2025-09-02 15:43:26 +08:00
parent ab8524e5ef
commit 15e1ed41f4
5 changed files with 297 additions and 70 deletions
+80 -35
View File
@@ -1,46 +1,91 @@
package convx
import (
"errors"
"encoding/json"
"fmt"
"reflect"
"strconv"
"time"
)
// interface 转 string
func ToString(val interface{}) (str string, err error) {
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
// InterfaceToString 将任意interface转换为string
func ToString(v interface{}) string {
if v == nil {
return ""
}
return "", errors.New("can not convert to string")
// 获取值的反射对象
val := reflect.ValueOf(v)
// 处理指针类型:解引用直到获取到非指针值
for val.Kind() == reflect.Ptr {
if val.IsNil() {
return ""
}
val = val.Elem()
}
// 获取解引用后的实际值
actualValue := val.Interface()
// 根据具体类型进行处理
switch actual := actualValue.(type) {
case string:
return actual
case []byte:
return string(actual)
case error:
return actual.Error()
case bool:
return strconv.FormatBool(actual)
case int:
return strconv.Itoa(actual)
case int8:
return strconv.FormatInt(int64(actual), 10)
case int16:
return strconv.FormatInt(int64(actual), 10)
case int32:
return strconv.FormatInt(int64(actual), 10)
case int64:
return strconv.FormatInt(actual, 10)
case uint:
return strconv.FormatUint(uint64(actual), 10)
case uint8:
return strconv.FormatUint(uint64(actual), 10)
case uint16:
return strconv.FormatUint(uint64(actual), 10)
case uint32:
return strconv.FormatUint(uint64(actual), 10)
case uint64:
return strconv.FormatUint(actual, 10)
case float32:
return strconv.FormatFloat(float64(actual), 'f', -1, 32)
case float64:
return strconv.FormatFloat(actual, 'f', -1, 64)
case complex64:
return fmt.Sprint(actual)
case complex128:
return fmt.Sprint(actual)
case time.Time:
return actual.Format(time.RFC3339)
case time.Duration:
return actual.String()
case fmt.Stringer:
return actual.String()
}
// 处理切片、数组、map、结构体等复杂类型 - 使用JSON序列化
if val.IsValid() {
switch val.Kind() {
case reflect.Slice, reflect.Array, reflect.Map, reflect.Struct:
jsonBytes, err := json.Marshal(actualValue)
if err == nil {
return string(jsonBytes)
}
}
}
// 默认处理:使用fmt.Sprint
return fmt.Sprint(actualValue)
}