登录
首页 >  Golang >  Go问答

避免在数据结构中使用嵌套映射的方法

来源:stackoverflow

时间:2024-02-17 18:18:22 179浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《避免在数据结构中使用嵌套映射的方法》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我有一个下面的结构,其中有一个 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


正确答案


在将值放入映射之前,您不需要分配映射。

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
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>