Principal
Necesitas escribir una biblioteca simple de caché en memoria. type Cache interface { Set(k, v string) Get(k string) (v string, ok bool) }
sobes.tech AI
Respuesta de la IA
A continuación, un ejemplo de implementación sencilla de una caché en memoria en Go, que cumple con la interfaz:
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
}
Aquí se utiliza un mutex para acceso seguro a la memoria compartida. Este tipo de caché almacena datos en memoria hasta que se reinicia la aplicación.