Use a sync.Map or a map protected by a sync.RWMutex to create a thread-safe generic cache in Go. The sync.Map is optimized for high concurrency with distinct keys, while a mutex-protected map offers better performance for frequent updates or iteration.
package main
import (
"fmt"
"sync"
)
type Cache[K comparable, V any] struct {
m sync.Map
}
func (c *Cache[K, V]) Get(key K) (V, bool) {
if v, ok := c.m.Load(key); ok {
return v.(V), true
}
var zero V
return zero, false
}
func (c *Cache[K, V]) Set(key K, value V) {
c.m.Store(key, value)
}
func (c *Cache[K, V]) Delete(key K) {
c.m.Delete(key)
}
func main() {
cache := &Cache[string, int]{}
cache.Set("count", 42)
if val, ok := cache.Get("count"); ok {
fmt.Println(val) // 42
}
}