douqi2571 2019-02-16 15:10 采纳率: 0%
浏览 32
已采纳

创建新映射时是否可以初始化映射的值?

I am working with a map that goes from byte arrays to 2D lists whose separate list elements are unsigned 32 bit integers. i.e. map[[8]byte][][]uint32

Currently, I have logic that checks to see if the 2D list is populated, and if it isn't, I add two empty lists. From there I can begin to actually fill these lists. Like so:

my_map := make(map[[8]byte][][]uint32)
/* Some logic to define x and i */
if len(my_map[x]) == 0 {
    /* Create two fresh inner-lists */
}
my_map[x][0] = append(my_map[x][0], uint32(i))

However, that isn't the most elegant, nor efficient seeming solution. I was wondering if GO had a way to automatically populate a map's 2D list values with inner lists upon creation of a new mapping. Alternatively, if there is a better datatype to be using, I am all ears.

Essentially, here is what I want to be able to do:

my_map := make(map[[8]byte][][]uint32)
/* Some logic to define x and i */
my_map[x][0] = append(my_map[x][0], uint32(i))
  • 写回答

1条回答 默认 最新

  • douxi6903 2019-02-16 16:32
    关注

    The default value for slices is nil, which append can work with. You can do this:

    package main
    
    import "fmt"
    
    func main() {
        m := make(map[string][]int)
        m["test0"] = append(m["test0"], 10)
        m["test1"] = append(m["test1"], 10)
        m["test2"] = append(m["test2"], 10)
        fmt.Println(m)
    }
    

    However, your case is trickier because your values are slices of slices. The default nil will not do in this case, because you're dereferencing a nil with my_map[x][0]. So you'll have to explicitly check if the [0] index was already allocated. There's nothing particularly inefficient about it, IMHO. It has the advantage of being explicit, so you can see exactly where things get allocated.

    If you wish, you can encapsulate this functionality into a function.

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

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳