为了账号安全,请及时绑定邮箱和手机立即绑定

如何避免我的数据结构中的嵌套映射分配?

如何避免我的数据结构中的嵌套映射分配?

Go
慕尼黑5688855 2022-12-26 15:43:03
我有一个下面的结构,其中有一个嵌套映射,CustomersIndex它分配了一堆内部映射,导致内存增加。我对它进行了分析,所以我注意到了这一点。我想看看是否有任何方法可以重新设计CustomersIndex不使用嵌套映射的数据结构?const (    departmentsKey = "departments")type CustomerManifest struct {    Customers      []definitions.Customer    CustomersIndex map[int]map[int]definitions.Customer}这是我在下面的代码中填充它的方式:func updateData(mdmCache *mdm.Cache) map[string]interface{} {    memCache := mdmCache.MemCache()    var customers []definitions.Customer    var customersIndex = map[int]map[int]definitions.Customer{}    for _, r := range memCache.Customer {        customer := definitions.Customer{            Id:           int(r.Id),            SetId:        int(r.DepartmentSetId),        }        customers = append(customers, customer)        _, yes := customersIndex[customer.SetId]        if !yes {            customersIndex[customer.SetId] = make(map[int]definitions.Customer)        }        customersIndex[customer.SetId][customer.Id] = customer    }    return map[string]interface{}{        departmentsKey: &CustomerManifest{Customers: customers, CustomersIndex: customersIndex},    }}这就是我获取CustomersIndex嵌套地图的方式。func (c *Client) GetCustomerIndex() map[int]map[int]definitions.Customer {    c.mutex.RLock()    defer c.mutex.RUnlock()    customersIndex := c.data[departmentsKey].(*CustomerManifest).CustomersIndex    return customersIndex}有什么方法可以CustomersIndex让我不必使用嵌套地图来设计我的地图吗?
查看完整描述

1 回答

?
慕哥6287543

TA贡献1831条经验 获得超10个赞

在将值放入其中之前,您不需要分配地图。


type CustomerManifest struct {

    Customers      []definitions.Customer

    CustomersIndex map[int]map[int]definitions.Customer

}


func (m *CustomerManifest) AddCustomerDefinition(x, y int, customer definitions.Customer) {

    // Get the existing map, if exists.

    innerMap := m.CustomersIndex[x]

    // If it doesn't exist, allocate it.

    if innerMap == nil {

        innerMap = make(map[int]definitions.Customer)

        m.CustomersIndex[x] = innerMap

    }

    // Add the value to the inner map, which now exists.

    innerMap[y] = customer

}


查看完整回答
反对 回复 2022-12-26
  • 1 回答
  • 0 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号