github.com/sandwich-go/boost@v1.3.29/xstrings/from.go (about) 1 package xstrings 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "reflect" 7 "strconv" 8 "time" 9 10 "github.com/sandwich-go/boost/z" 11 ) 12 13 // iString is used for type assert api for String(). 14 type iString interface { 15 String() string 16 } 17 18 // From [影响性能] converts `any` to string. 19 func From(any interface{}) string { 20 if any == nil { 21 return "" 22 } 23 switch value := any.(type) { 24 case int: 25 return strconv.Itoa(value) 26 case int8: 27 return strconv.Itoa(int(value)) 28 case int16: 29 return strconv.Itoa(int(value)) 30 case int32: 31 return strconv.Itoa(int(value)) 32 case int64: 33 return strconv.FormatInt(value, 10) 34 case uint: 35 return strconv.FormatUint(uint64(value), 10) 36 case uint8: 37 return strconv.FormatUint(uint64(value), 10) 38 case uint16: 39 return strconv.FormatUint(uint64(value), 10) 40 case uint32: 41 return strconv.FormatUint(uint64(value), 10) 42 case uint64: 43 return strconv.FormatUint(value, 10) 44 case float32: 45 return strconv.FormatFloat(float64(value), 'f', -1, 32) 46 case float64: 47 return strconv.FormatFloat(value, 'f', -1, 64) 48 case bool: 49 return strconv.FormatBool(value) 50 case string: 51 return value 52 case []byte: 53 return string(value) 54 case time.Time: 55 if value.IsZero() { 56 return "" 57 } 58 return value.String() 59 case *time.Time: 60 if value == nil { 61 return "" 62 } 63 return value.String() 64 default: 65 // Empty checks. 66 if value == nil { 67 return "" 68 } 69 if f, ok := value.(iString); ok { 70 return f.String() 71 } 72 if f, ok := value.(error); ok { 73 return f.Error() 74 } 75 // Reflect checks. 76 var ( 77 rv = reflect.ValueOf(value) 78 kind = rv.Kind() 79 ) 80 switch kind { 81 case reflect.Chan, 82 reflect.Map, 83 reflect.Slice, 84 reflect.Func, 85 reflect.Ptr, 86 reflect.Interface, 87 reflect.UnsafePointer: 88 if rv.IsNil() { 89 return "" 90 } 91 case reflect.String: 92 return rv.String() 93 } 94 if kind == reflect.Ptr { 95 return From(rv.Elem().Interface()) 96 } 97 if jsonContent, err := json.Marshal(value); err != nil { 98 return fmt.Sprint(value) 99 } else { 100 return z.BytesToString(jsonContent) 101 } 102 } 103 }