vendredi 20 mars 2020

How to dereference a pointer value from interface{} (Current solutions on stackoverflow doesn't work)

MapJsonTagsToFieldName is generic function I wrote that given a struct it will return a map, mapping json tags to field names.

id -> Id
name -> Name

The problem is that it looks like Go reflection in this case can only work when the object is a struct and not a pointer to a struct. Because this is a generic function I don't know what kind of struct is there.

How can I get the actual object from the 'obj' parameter so that this function will work? I tried to use Elem() and Indirect() and it still doesn't work

type User struct{
    Id int64        `json:"id"`
    Name string     `json:"name"`
}

func Run() {

    p1 := &User{1,"foo"}

    // This works
    MapJsonTagsToFieldName(*p1) // Sending object

    // This doesn't works
    MapJsonTagsToFieldName(p1) //Sending pointer
}

func MapJsonTagsToFieldName(obj interface{}) map[string]string {
    res := make(map[string]string)
    t := reflect.TypeOf(obj)
    // This option also doesn't work
    // t := reflect.TypeOf(reflect.ValueOf(obj).Elem())
    for i := 0; i < t.NumField(); i++ {
        jsonTag := t.Elem().Field(i).Tag.Get("json")
        res[jsonTag] = t.Field(i).Name
    }

    return res
}




Aucun commentaire:

Enregistrer un commentaire