How to get underlying value from a reflect.Value in golang?

前端 未结 4 1518
星月不相逢
星月不相逢 2021-02-02 08:02

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

4条回答
  •  太阳男子
    2021-02-02 08:23

    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.

提交回复
热议问题