如何在不覆盖现有数据的情况下将键值添加到变量?
How do I add key-value to variable without overriding existing data?
我正在尝试仅使用一个变量来创建一个简单的缓存,但我不知道如何在每次不完全覆盖它的情况下添加它。
这是一个片段:
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()
来创建存储切片 - 但我不想这样做,因为我相信我会丢失切片中已有的任何内容,使其变得无用。
我如何在 go 中执行此操作?
您正在创建一个全局变量存储,而您很可能想将它封装在您的 Routes 结构中:
package main
type Routes struct{
store map[string][]byte
}
func NewRoutes() *Routes {
return &Routes{
store: make(map[string][]byte),
}
}
func (c *Routes) SetRoutes(key string, routes []byte) error {
c.store[key] = routes
return nil
}
func main() {
routes := NewRoutes()
routes.SetRoutes("key", []byte("routes"))
}
参见:https://go.dev/play/p/3M4kAfya6KE。这可确保地图的范围限定为您的 Routes 结构并且仅初始化一次。
您可以检查它是否是 nil
和 make
如果是:
func (c *Routes) SetRoutes(key string, routes []byte) error {
if store == nil {
store = make(map[string][]byte)
}
store[key] = routes
return nil
}
或者,只需在 main
func:
func main() {
store = make(map[string][]byte)
routes := NewRoutes()
routes.SetRoutes("key", []byte("routes"))
}
我正在尝试仅使用一个变量来创建一个简单的缓存,但我不知道如何在每次不完全覆盖它的情况下添加它。
这是一个片段:
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()
来创建存储切片 - 但我不想这样做,因为我相信我会丢失切片中已有的任何内容,使其变得无用。
我如何在 go 中执行此操作?
您正在创建一个全局变量存储,而您很可能想将它封装在您的 Routes 结构中:
package main
type Routes struct{
store map[string][]byte
}
func NewRoutes() *Routes {
return &Routes{
store: make(map[string][]byte),
}
}
func (c *Routes) SetRoutes(key string, routes []byte) error {
c.store[key] = routes
return nil
}
func main() {
routes := NewRoutes()
routes.SetRoutes("key", []byte("routes"))
}
参见:https://go.dev/play/p/3M4kAfya6KE。这可确保地图的范围限定为您的 Routes 结构并且仅初始化一次。
您可以检查它是否是 nil
和 make
如果是:
func (c *Routes) SetRoutes(key string, routes []byte) error {
if store == nil {
store = make(map[string][]byte)
}
store[key] = routes
return nil
}
或者,只需在 main
func:
func main() {
store = make(map[string][]byte)
routes := NewRoutes()
routes.SetRoutes("key", []byte("routes"))
}