我有一个下面的结构,其中有一个嵌套映射,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
}
- 1 回答
- 0 关注
- 119 浏览
添加回答
举报
0/150
提交
取消
