tostring_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Formatting of reflection types and values for debugging.
  5. // Not defined as methods so they do not need to be linked into most binaries;
  6. // the functions are not used by the library itself, only in tests.
  7. package reflect_test
  8. import (
  9. . "reflect"
  10. "strconv"
  11. )
  12. // valueToString returns a textual representation of the reflection value val.
  13. // For debugging only.
  14. func valueToString(val Value) string {
  15. var str string
  16. if !val.IsValid() {
  17. return "<zero Value>"
  18. }
  19. typ := val.Type()
  20. switch val.Kind() {
  21. case Int, Int8, Int16, Int32, Int64:
  22. return strconv.FormatInt(val.Int(), 10)
  23. case Uint, Uint8, Uint16, Uint32, Uint64, Uintptr:
  24. return strconv.FormatUint(val.Uint(), 10)
  25. case Float32, Float64:
  26. return strconv.FormatFloat(val.Float(), 'g', -1, 64)
  27. case Complex64, Complex128:
  28. c := val.Complex()
  29. return strconv.FormatFloat(real(c), 'g', -1, 64) + "+" + strconv.FormatFloat(imag(c), 'g', -1, 64) + "i"
  30. case String:
  31. return val.String()
  32. case Bool:
  33. if val.Bool() {
  34. return "true"
  35. } else {
  36. return "false"
  37. }
  38. case Ptr:
  39. v := val
  40. str = typ.String() + "("
  41. if v.IsNil() {
  42. str += "0"
  43. } else {
  44. str += "&" + valueToString(v.Elem())
  45. }
  46. str += ")"
  47. return str
  48. case Array, Slice:
  49. v := val
  50. str += typ.String()
  51. str += "{"
  52. for i := 0; i < v.Len(); i++ {
  53. if i > 0 {
  54. str += ", "
  55. }
  56. str += valueToString(v.Index(i))
  57. }
  58. str += "}"
  59. return str
  60. case Map:
  61. t := typ
  62. str = t.String()
  63. str += "{"
  64. str += "<can't iterate on maps>"
  65. str += "}"
  66. return str
  67. case Chan:
  68. str = typ.String()
  69. return str
  70. case Struct:
  71. t := typ
  72. v := val
  73. str += t.String()
  74. str += "{"
  75. for i, n := 0, v.NumField(); i < n; i++ {
  76. if i > 0 {
  77. str += ", "
  78. }
  79. str += valueToString(v.Field(i))
  80. }
  81. str += "}"
  82. return str
  83. case Interface:
  84. return typ.String() + "(" + valueToString(val.Elem()) + ")"
  85. case Func:
  86. v := val
  87. return typ.String() + "(" + strconv.FormatUint(uint64(v.Pointer()), 10) + ")"
  88. default:
  89. panic("valueToString: can't print type " + typ.String())
  90. }
  91. }