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

Issue

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

Solution

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.

Answered By – Blokje5

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.