【发布时间】:2020-10-22 19:54:14
【问题描述】:
我正在学习 Go 中的 reflect 并尝试实现获取 map 并返回另一个 map 的函数,其中键是值,值是键。
例子:
m := map[string]int{"one": 1, "two": 2}
fmt.Println(ReverseMap(m)) // {1: "one", 2: "two"}
这是我的代码:
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
}
此代码panic 有错误:
恐慌:reflect.Value.SetMapIndex:int 类型的值不能分配给类型 reflect.Value
我认为这个错误的原因是out变量的声明,但是我不知道如何正确声明它,如果我不知道这个变量的类型。
我该如何解决这个错误?
【问题讨论】:
标签: dictionary go reflection