douqi2571 2019-02-16 07: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 08: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 求Houdini使用行家,付费。价格面议。
  • ¥15 AttributeError: 'EasyDict' object has no attribute 'BACKUP_DB_INFO'
  • ¥15 前端高拍仪调用问题报错
  • ¥15 想用octave解决这个数学问题
  • ¥15 Centos新建的临时ip无法上网,如何解决?
  • ¥15 海康威视如何实现客户端软件对设备语音请求的处理。
  • ¥15 支付宝h5参数如何实现跳转
  • ¥15 MATLAB代码补全插值
  • ¥15 Typegoose 中如何使用 arrayFilters 筛选并更新深度嵌套的子文档数组信息
  • ¥15 CF1927D 求Hack