So I found some code that help me get started with reflection in Go (golang), but I\'m having trouble getting a the underlying value so that I can basically create a map[s
It looks like you're on the right track. The problem I see with your code is it makes assumptions about the values, meaning when do you call Elem()
and how many times (to resolve pointers). In order to know this you need to look at the reflect.Kind
. Is the value a reflect.Ptr
? Then use Elem()
.
Once you have the value from val.Interface()
/ val.String()
/ val.Int()
you can convert your values as needed. What you use is going to depend on reflect.Kind
. To convert an int
to/from string
you need to use the strconv
package.
The encoding/json
and encoding/xml
packages do this kind of work already. The source code provides some great examples. For example, take a look at copyValue
in encoding/xml/read.go and marshalSimple
in encoding/xml/marshal.go.