To implement a cache using a map in Go, you can follow these steps:
Start by importing the necessary packages: "sync"
for synchronization and "time"
for time-based eviction.
Define the Cache
struct that encapsulates the cache map and other necessary fields:
type Cache struct {
cacheMap map[string]*CacheItem
mutex sync.RWMutex
maxSize int
eviction time.Duration
}
type CacheItem struct {
value interface{}
expiration *time.Time
}
Get
method to retrieve a value from the cache by key:func (c *Cache) Get(key string) (interface{}, bool) {
c.mutex.RLock()
defer c.mutex.RUnlock()
item, found := c.cacheMap[key]
if !found {
return nil, false
}
// Remove expired items
if item.expiration != nil && item.expiration.Before(time.Now()) {
c.deleteItem(key)
return nil, false
}
return item.value, true
}
Set
method to add or update a key-value pair in the cache:func (c *Cache) Set(key string, value interface{}, expiration *time.Duration) {
c.mutex.Lock()
defer c.mutex.Unlock()
// If the cache exceeds the maximum size, remove the oldest item
if len(c.cacheMap) >= c.maxSize {
c.evictOldest()
}
item := &CacheItem{value: value}
if expiration != nil {
expireTime := time.Now().Add(*expiration)
item.expiration = &expireTime
}
c.cacheMap[key] = item
}
Delete
method to remove a key-value pair from the cache:func (c *Cache) Delete(key string) {
c.mutex.Lock()
defer c.mutex.Unlock()
c.deleteItem(key)
}
evictOldest
method to remove the oldest item from the cache:func (c *Cache) evictOldest() {
var oldestKey string
var oldestTime *time.Time
for key, item := range c.cacheMap {
if oldestTime == nil || item.expiration != nil && item.expiration.Before(*oldestTime) {
oldestKey = key
oldestTime = item.expiration
}
}
c.deleteItem(oldestKey)
}
deleteItem
method to safely delete an item from the cache:func (c *Cache) deleteItem(key string) {
delete(c.cacheMap, key)
}
With these methods, you can create an instance of the Cache
struct and use it to store and retrieve data efficiently using a map as the underlying structure. Remember to set an appropriate maximum size for the cache and consider expiration time for the cached items if required.