Junior — Middle
What caching methods do you prefer to use in your projects and why?
sobes.tech AI
Answer from AI
In Go, the following approaches are often used for caching:
- Built-in data structures with synchronization: for example,
mapwithsync.RWMutexfor thread-safe access. - Third-party libraries: for example,
golang-lrufor implementing an LRU cache that automatically removes the least used items. - sync.Map: a thread-safe map from the standard library, convenient for caches with high contention.
The choice depends on the task:
- For a simple cache with access control —
map+sync.RWMutex. - For a cache with size limits and automatic removal — an LRU cache from third-party libraries.
- For high-performance cases with frequent reads and infrequent writes —
sync.Map.
Example of a simple cache with sync.RWMutex:
Type Cache struct {
mu sync.RWMutex
data map[string]interface{}
}
func (c *Cache) Get(key string) (interface{}, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
val, ok := c.data[key]
return val, ok
}
func (c *Cache) Set(key string, value interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
c.data[key] = value
}
This approach is simple and effective for most cases.