github.com/sandwich-go/boost@v1.3.29/xconv/string.go (about)

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