Principal
Este necesar să scrieți o bibliotecă simplă de cache în memorie. type Cache interface { Set(k, v string) Get(k string) (v string, ok bool) }
sobes.tech AI
Răspuns de la AI
Mai jos este un exemplu simplu de implementare a unui cache în memorie în Go, care corespunde interfeței:
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
}
Aici, se folosește un mutex pentru acces sigur la hartă. Acest cache stochează date în memorie până la repornirea aplicației.