我有类似的东西type rateLimit struct { Count int}type RateLimiter struct { cachePeriod time.Duration rateLimits map[string]*rateLimit}和这样的功能:func NewRateLimiter(////) *RateLimiter { rateLimits := make(map[string]*rateLimit) return &RateLimiter{ cachePeriod: cachePeriod, rateLimits: rateLimits, }}此结构允许您创建嵌套结构,例如 rateLimits["foo"] = a但我正在尝试进行更改以使其嵌套并且我可以做到rateLimits["foo"]["bar"] = a我尝试将结构更改为 rateLimits := make(map[string]map[string]*rateLimit)和type rateLimiter struct { cachePeriod time.Duration rateLimits map[string]map[string]*rateLimit}但我得到panic: assignment to entry in nil map [recovered] panic: assignment to entry in nil map
2 回答
qq_遁去的一_1
TA贡献1725条经验 获得超7个赞
rateLimits := make(map[string]map[string]*rateLimit)
rateLimits["foo"] = make(map[string]*rateLimit)
rateLimits["foo"]["bar"] = a
rateLimits := map[string]map[string]*rateLimit{"foo": {"bar": a}}
白衣染霜花
TA贡献1796条经验 获得超10个赞
您必须制作嵌套地图:
func setNested(m1 map[string]map[string]string, k1, k2 string, v string) {
m2 := m1[k1]
if m2 == nil {
m2 = make(map[string]string)
m1[k1] = m2
}
m2[k2] = v
}
像这样使用它:
setNested(rateLimits, "foo", "bar", a)
- 2 回答
- 0 关注
- 121 浏览
添加回答
举报
0/150
提交
取消