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