jeudi 2 juillet 2020

How can I reverse map using reflection

I am studying reflect in Go and trying to implement function which get map and return another map, where keys will be values and values will be keys.

Example:

m := map[string]int{"one": 1, "two": 2}
fmt.Println(ReverseMap(m)) // {1: "one", 2: "two"}

Here is my code:

func ReverseMap(in interface{}) interface{} {

    var out reflect.Value
    v := reflect.ValueOf(in)
    if v.Kind() == reflect.Map {
        for idx, key := range v.MapKeys() {
            value := v.MapIndex(key)
            if idx == 0 {
                mapType := reflect.MapOf(reflect.TypeOf(value), reflect.TypeOf(key))
                out = reflect.MakeMap(mapType)
            }
            out.SetMapIndex(value, key)
        }
    }
    return out
}

This code panic with error:

panic: reflect.Value.SetMapIndex: value of type int is not assignable to type reflect.Value

I think the reason of this error is the declaration of out variable, but I don't know how to declare it correctly, if I don't know the type of this variable.

How can I fix this error?





Aucun commentaire:

Enregistrer un commentaire