我正在尝试仅使用一个变量创建一个简单的缓存,但我不知道如何添加到它而不每次都完全覆盖它。
这是一个片段:
package main
var store map[string][]byte
type Routes struct{}
func NewRoutes() *Routes {
return &Routes{}
}
func (c *Routes) SetRoutes(key string, routes []byte) error {
store[key] = routes
return nil
}
func main() {
routes := NewRoutes()
routes.SetRoutes("key", []byte("routes"))
}
这将导致panic: assignment to entry in nil map. 我可以make()用来创建商店切片 - 但我不想这样做,因为我相信我会丢失切片中已经存在的任何东西,使其变得无用。
我怎么能这样做呢?
https://go.dev/play/p/NbqSbSTx5ER
jeck猫
跃然一笑
相关分类