1
0

lang.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package lang
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strconv"
  6. )
  7. // Placeholder is a placeholder object that can be used globally.
  8. var Placeholder PlaceholderType
  9. type (
  10. // AnyType can be used to hold any type.
  11. AnyType = any
  12. // PlaceholderType represents a placeholder type.
  13. PlaceholderType = struct{}
  14. )
  15. // Repr returns the string representation of v.
  16. func Repr(v any) string {
  17. if v == nil {
  18. return ""
  19. }
  20. // if func (v *Type) String() string, we can't use Elem()
  21. switch vt := v.(type) {
  22. case fmt.Stringer:
  23. return vt.String()
  24. }
  25. val := reflect.ValueOf(v)
  26. for val.Kind() == reflect.Ptr && !val.IsNil() {
  27. val = val.Elem()
  28. }
  29. return reprOfValue(val)
  30. }
  31. func reprOfValue(val reflect.Value) string {
  32. switch vt := val.Interface().(type) {
  33. case bool:
  34. return strconv.FormatBool(vt)
  35. case error:
  36. return vt.Error()
  37. case float32:
  38. return strconv.FormatFloat(float64(vt), 'f', -1, 32)
  39. case float64:
  40. return strconv.FormatFloat(vt, 'f', -1, 64)
  41. case fmt.Stringer:
  42. return vt.String()
  43. case int:
  44. return strconv.Itoa(vt)
  45. case int8:
  46. return strconv.Itoa(int(vt))
  47. case int16:
  48. return strconv.Itoa(int(vt))
  49. case int32:
  50. return strconv.Itoa(int(vt))
  51. case int64:
  52. return strconv.FormatInt(vt, 10)
  53. case string:
  54. return vt
  55. case uint:
  56. return strconv.FormatUint(uint64(vt), 10)
  57. case uint8:
  58. return strconv.FormatUint(uint64(vt), 10)
  59. case uint16:
  60. return strconv.FormatUint(uint64(vt), 10)
  61. case uint32:
  62. return strconv.FormatUint(uint64(vt), 10)
  63. case uint64:
  64. return strconv.FormatUint(vt, 10)
  65. case []byte:
  66. return string(vt)
  67. default:
  68. return fmt.Sprint(val.Interface())
  69. }
  70. }