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 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题