Principal
Vous devez écrire une bibliothèque simple de cache en mémoire. type Cache interface { Set(k, v string) Get(k string) (v string, ok bool) }
sobes.tech IA
Réponse de l'IA
Voici un exemple simple d'implémentation d'un cache en mémoire en Go, conforme à l'interface :
type Cache interface {
Set(k, v string)
Get(k string) (v string, ok bool)
}
type SimpleCache struct {
data map[string]string
mu sync.RWMutex
}
func NewSimpleCache() *SimpleCache {
return &SimpleCache{
data: make(map[string]string),
}
}
func (c *SimpleCache) Set(k, v string) {
c.mu.Lock()
defer c.mu.Unlock()
c.data[k] = v
}
func (c *SimpleCache) Get(k string) (string, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
v, ok := c.data[k]
return v, ok
}
Ici, un mutex est utilisé pour un accès sécurisé à la carte. Ce cache stocke les données en mémoire jusqu'à ce que l'application soit redémarrée.