'How do I add key-value to variable without overriding existing data?
I am trying to create a simple cache just using a variable and I don't know how to add to it without completely overriding it each time.
Here is a snippet:
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"))
}
This will result in panic: assignment to entry in nil map. I can use make() to create the store slice - but I don't want to do that as I believe I would lose whatever was already in the slice rendering it useless.
How can I do this in go?
Solution 1:[1]
You are creating a global variable store, while most likely you want to encapsulate it in your Routes struct:
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"))
}
See: https://go.dev/play/p/3M4kAfya6KE. This ensures the map is scoped to your Routes struct and only initialised once.
Solution 2:[2]
You can check if it is nil and make if it is:
func (c *Routes) SetRoutes(key string, routes []byte) error {
if store == nil {
store = make(map[string][]byte)
}
store[key] = routes
return nil
}
Alternatively, just make it in the main func:
func main() {
store = make(map[string][]byte)
routes := NewRoutes()
routes.SetRoutes("key", []byte("routes"))
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Blokje5 |
| Solution 2 | twharmon |
