Home > database >  How do I add key-value to variable without overriding existing data?
How do I add key-value to variable without overriding existing data?

Time:03-17

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?

https://go.dev/play/p/NbqSbSTx5ER

CodePudding user response:

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.

CodePudding user response:

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"))
}
  •  Tags:  
  • go
  • Related