doushifen4060 2016-01-13 07:52

# Golang：如何创建未知（动态）贴图长度

I can create a "static" map via

``````type m map[int]map[int]map[int]bool
``````

but the length of "keys" will be dynamic:

`````` |---unknown len--|
m[1][2][3][4][2][0] = true
``````

or

``````|---unk len--|
m[1][2][3][4] = true
``````

How I can create this map in Go? Or any way exists?

• 写回答

#### 4条回答默认 最新

• doucuo8618 2016-01-13 08:56
关注

Ok I had some fun playing with this a bit. Here is a much better implementation than what I did before:

``````type mymap map[int]*myentry

type myentry struct {
m mymap
b bool
}

func (mm mymap) get(idx ...int) *myentry {
if len(idx) == 0 {
return nil
}
entry, ok := mm[idx[0]]
if !ok {
return nil
} else if len(idx) == 1 {
return entry
}
for i := 1; i < len(idx); i++ {
if entry == nil || entry.m == nil {
return nil
}
entry = entry.m[idx[i]]
}
return entry
}

func (mm mymap) setbool(v bool, idx ...int) {
if len(idx) == 0 {
return
}
if mm[idx[0]] == nil {
mm[idx[0]] = &myentry{m: make(mymap), b: false}
} else if mm[idx[0]].m == nil {
mm[idx[0]].m = make(mymap)
}
if len(idx) == 1 {
mm[idx[0]].b = v
return
}
entry := mm[idx[0]]
for i := 1; i < len(idx); i++ {
if entry.m == nil {
entry.m = make(mymap)
entry.m[idx[i]] = &myentry{m: make(mymap), b: false}
} else if entry.m[idx[i]] == nil {
entry.m[idx[i]] = &myentry{m: make(mymap), b: false}
}
entry = entry.m[idx[i]]
}
entry.b = v
}

func (m mymap) getbool(idx ...int) bool {
if val := m.get(idx...); val != nil {
return val.b
}
return false
}

func (m mymap) getmap(idx ...int) mymap {
if val := m.get(idx...); val != nil {
return val.m
}
return nil
}
``````

Something like that ought to get you started

本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 C++代码实现将空白光盘设置为U盘模式
• ¥15 求解,游戏闪退报错005
• ¥15 au3程序，按键执行程序
• ¥15 js函数，数组语法写一个检测函数
• ¥15 burp并发插件卡住了没反应
• ¥15 Linux分区格式化后挂载4TB新硬盘显示无法识别filesystem
• ¥15 燃机的MPC控制器代码问题
• ¥15 powershell删除目录及文件空格等符号问题
• ¥20 微信h5网页如何静默获取到用户的基本信息（头像昵称）
• ¥15 如图所示交换机网络该如何规划配置