Skip to content

Instantly share code, notes, and snippets.

@niski84
Created December 9, 2022 09:12
Show Gist options
  • Save niski84/5aceaa2e88d7378f688f7b69f3ba464d to your computer and use it in GitHub Desktop.
Save niski84/5aceaa2e88d7378f688f7b69f3ba464d to your computer and use it in GitHub Desktop.
implementing a safe cache
type Cache struct {
items map[string]interface{}
mu sync.Mutex
}
func NewCache() *Cache {
return &Cache{
items: make(map[string]interface{}),
}
}
func (c *Cache) Set(key string, value interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = value
}
func (c *Cache) Get(key string) (interface{}, bool) {
c.mu.Lock()
defer c.mu.Unlock()
val, ok := c.items[key]
return val, ok
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment