mirror of
https://github.com/jefferyjob/go-easy-utils.git
synced 2025-09-28 20:02:11 +08:00
43 lines
983 B
Go
43 lines
983 B
Go
package jsonx
|
|
|
|
import (
|
|
"fmt"
|
|
"reflect"
|
|
"strconv"
|
|
)
|
|
|
|
func toStringReflect(i any) string {
|
|
if i == nil {
|
|
return ""
|
|
}
|
|
|
|
v := reflect.ValueOf(i)
|
|
if v.Kind() == reflect.Ptr {
|
|
if v.IsNil() {
|
|
return ""
|
|
}
|
|
v = v.Elem()
|
|
}
|
|
|
|
switch v.Kind() {
|
|
case reflect.String:
|
|
return v.String()
|
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
return strconv.FormatInt(v.Int(), 10)
|
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
|
return strconv.FormatUint(v.Uint(), 10)
|
|
case reflect.Float32:
|
|
return strconv.FormatFloat(v.Float(), 'f', -1, 32)
|
|
case reflect.Float64:
|
|
return strconv.FormatFloat(v.Float(), 'f', -1, 64)
|
|
case reflect.Complex64:
|
|
return fmt.Sprintf("(%g+%gi)", real(v.Complex()), imag(v.Complex()))
|
|
case reflect.Complex128:
|
|
return fmt.Sprintf("(%g+%gi)", real(v.Complex()), imag(v.Complex()))
|
|
case reflect.Bool:
|
|
return strconv.FormatBool(v.Bool())
|
|
default:
|
|
return ""
|
|
}
|
|
}
|