How to implement a cache using a map in Go?

To implement a cache using a map in Go, you can follow these steps:

  1. Start by importing the necessary packages: "sync" for synchronization and "time" for time-based eviction.

  2. 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 }
  1. Create a struct to hold the cache items with additional metadata:
type CacheItem struct { value interface{} expiration *time.Time }
  1. Implement the 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 }
  1. Implement the 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 }
  1. Implement the 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) }
  1. Implement the 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) }
  1. Finally, implement the 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.