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