github.com/FISCO-BCOS/crypto@v0.0.0-20200202032121-bd8ab0b5d4f1/internal/reflectlite/tostring_test.go (about) 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 5 // Formatting of reflection types and values for debugging. 6 // Not defined as methods so they do not need to be linked into most binaries; 7 // the functions are not used by the library itself, only in tests. 8 9 package reflectlite_test 10 11 import ( 12 . "internal/reflectlite" 13 "reflect" 14 "strconv" 15 ) 16 17 // valueToString returns a textual representation of the reflection value val. 18 // For debugging only. 19 func valueToString(v Value) string { 20 return valueToStringImpl(reflect.ValueOf(ToInterface(v))) 21 } 22 23 func valueToStringImpl(val reflect.Value) string { 24 var str string 25 if !val.IsValid() { 26 return "<zero Value>" 27 } 28 typ := val.Type() 29 switch val.Kind() { 30 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 31 return strconv.FormatInt(val.Int(), 10) 32 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 33 return strconv.FormatUint(val.Uint(), 10) 34 case reflect.Float32, reflect.Float64: 35 return strconv.FormatFloat(val.Float(), 'g', -1, 64) 36 case reflect.Complex64, reflect.Complex128: 37 c := val.Complex() 38 return strconv.FormatFloat(real(c), 'g', -1, 64) + "+" + strconv.FormatFloat(imag(c), 'g', -1, 64) + "i" 39 case reflect.String: 40 return val.String() 41 case reflect.Bool: 42 if val.Bool() { 43 return "true" 44 } else { 45 return "false" 46 } 47 case reflect.Ptr: 48 v := val 49 str = typ.String() + "(" 50 if v.IsNil() { 51 str += "0" 52 } else { 53 str += "&" + valueToStringImpl(v.Elem()) 54 } 55 str += ")" 56 return str 57 case reflect.Array, reflect.Slice: 58 v := val 59 str += typ.String() 60 str += "{" 61 for i := 0; i < v.Len(); i++ { 62 if i > 0 { 63 str += ", " 64 } 65 str += valueToStringImpl(v.Index(i)) 66 } 67 str += "}" 68 return str 69 case reflect.Map: 70 str += typ.String() 71 str += "{" 72 str += "<can't iterate on maps>" 73 str += "}" 74 return str 75 case reflect.Chan: 76 str = typ.String() 77 return str 78 case reflect.Struct: 79 t := typ 80 v := val 81 str += t.String() 82 str += "{" 83 for i, n := 0, v.NumField(); i < n; i++ { 84 if i > 0 { 85 str += ", " 86 } 87 str += valueToStringImpl(v.Field(i)) 88 } 89 str += "}" 90 return str 91 case reflect.Interface: 92 return typ.String() + "(" + valueToStringImpl(val.Elem()) + ")" 93 case reflect.Func: 94 return typ.String() + "(arg)" 95 default: 96 panic("valueToString: can't print type " + typ.String()) 97 } 98 }