mercredi 16 février 2022

How can I modify a reflection object in golang when type is interface type

I try to set a map type with reflection.

However, the program will panic that is "using unaddressable value".

I call CanSet() func that return false that represent it cannot set.

I can get a addressable value if value type isn't interface type.

I know that I should call Elem() twice for getting addressable value but it still panic.

Why the result is different?

How can I fix this in the general case?

The following is example code

func main() {
    var obj = Test{}
    TestFunc(obj)
}

func TestFunc(obj interface{}) {
    objValueType := reflect.ValueOf(&obj).Elem().Elem()
    infoValueType := objValueType.FieldByName("TestInfo")
    mapValueType := infoValueType.FieldByName("TestMap")

    maps := map[string]*TestInfoDetail{}
    maps["1111"] = &TestInfoDetail{Key: "AAAA"}
    maps["2222"] = &TestInfoDetail{Key: "BBBB"}
    mapType := reflect.ValueOf(maps)

    mapValueType.Set(mapType)
    mapValueType.SetMapIndex(reflect.ValueOf("3333"), reflect.ValueOf(&TestInfoDetail{Key: "WOWO"}))
    maps, ok := mapValueType.Interface().(map[string]*TestInfoDetail)
    if ok {
        for _, item := range maps {
            fmt.Println(item.Key)
        }
    }
}

Thanks.





Aucun commentaire:

Enregistrer un commentaire