从键数组和值构建任意深度的嵌套映射



我希望能够编写一个 GoLang 函数来获取键数组和一个值(即keys={"a", "b", "c"}, value=123( 然后构建嵌套映射的数据结构,其中数组中的位置索引对应于嵌套映射中的深度,并将值分配给最后一个键。例如,给定上述键和值,我想构建以下字典结构

{"a":{"b":{"c":123}}}

以下是我目前拥有的代码。问题是生成的地图如下所示

{"a":{}, "b":{}, "c":123}.

关于我应该如何修改它/为什么会发生的任何建议将不胜感激。

import (
"fmt"
)
type dict map[interface{}]interface{}
func main() {
vals := []interface{}{"a", "b", "c"}
// create a dictionary
d := make(dict)
d.Set(vals, 123)
// print it
fmt.Println(d)
}
func (d dict) Set(keys []interface{}, value interface{}) {
d2 := d
fmt.Println("Initial dict: ", d2)
keylen := len(keys)-1
for _, key := range keys[:keylen] {
// if key exists, recurse into that part of the dict
if entry, ok := d2[key]; ok {
d2 := entry
fmt.Println("Entered level in dict: ", d2)
} else {
d3 := make(dict)
d2[key] = d3
d2 := d3
fmt.Println("Created new level in dict: ", d2)
}
}
d2[keys[keylen]] = value
fmt.Println("Final dict: ", d2)
}

您的解决方案似乎过于复杂。这个递归算法应该做:

func set(d dict,keys []interface{}, value interface{}) {
if len(keys)==1 {
d[keys[0]]=value
return
}
v, ok:=d[keys[0]]
if !ok {
v=dict{}
d[keys[0]]=v
}
set(v.(dict),keys[1:],value)
}

您必须添加代码来处理重置值的情况(即当 v.(dict( 类型断言可能失败时(。否则,您可以递归下降映射,并同时使用密钥。

最新更新