github.com/yandex/pandora@v0.5.32/lib/str/format.go (about)

     1  package str
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"reflect"
     7  	"strconv"
     8  )
     9  
    10  func FormatString(iface any) string {
    11  	switch val := iface.(type) {
    12  	case []byte:
    13  		return string(val)
    14  	}
    15  	v := reflect.ValueOf(iface)
    16  	switch v.Kind() {
    17  	case reflect.Invalid:
    18  		return ""
    19  	case reflect.Bool:
    20  		return strconv.FormatBool(v.Bool())
    21  	case reflect.String:
    22  		return v.String()
    23  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
    24  		return strconv.FormatInt(v.Int(), 10)
    25  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
    26  		return strconv.FormatUint(v.Uint(), 10)
    27  	case reflect.Float64:
    28  		return strconv.FormatFloat(v.Float(), 'f', -1, 64)
    29  	case reflect.Float32:
    30  		return strconv.FormatFloat(v.Float(), 'f', -1, 32)
    31  	case reflect.Ptr:
    32  		b, err := json.Marshal(v.Interface())
    33  		if err != nil {
    34  			return "nil"
    35  		}
    36  		return string(b)
    37  	}
    38  	return fmt.Sprintf("%v", iface)
    39  }