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

前端 未结 4 1520
星月不相逢
星月不相逢 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:33

    A good example of how to parse values is the fmt package. See this code.

    Using the mentioned code to match your problem would look like this:

    switch val.Kind() {
    case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
        m[typeField.Name] = strconv.FormatInt(val.Int(), 10)
    case reflect.String:
        m[typeField.Name] = val.String()    
    // etc...
    }
    

    Basically you need to check for all available Kinds.

提交回复
热议问题