A cache stores previously retrieved or computed values under keys so they can be reused instead of obtained again. It is useful when obtaining a value is costly and a previously obtained value is still acceptable. section 7.0 section 7.6
Cache exchange rates
A money converter that fetches rates for every run may make identical HTTP calls for a long list of amounts. One approach is to save rates in a temporary file named with the date: fetch them if the file is missing or too old, otherwise load it. A separate flag can flush the cache. The acceptable age matters because exchange rates change. section 6.6.1 section 7.0
A simple Go cache can use a generic map. Keys must satisfy comparable; values can be any type. Initialize the map in a constructor, then provide operations to read, insert or replace, and delete entries. A read returns the value and a boolean indicating whether it was found. section 7.1.3
Listing 7.1 cache.go
// Cache is key-value storage.
type Cache[K comparable, V any] struct {
data map[K]V
}
The initial cache stores parameterized keys and values in a map. section 7.1.3
Storing values directly avoids requiring every caller to supply pointers; callers can still choose a pointer as the value type. The choice involves a memory-versus-indirection tradeoff. section 7.1.3
A practical cache needs policies beyond basic storage:
- Concurrency: protect shared cache operations with a mutex. A sequential test alone cannot establish safety when multiple goroutines access the cache. section 7.3 section 7.4.2
- Freshness: assign a time to live (TTL) so outdated entries can be treated as absent. Choose the lifetime according to how stale the answer may be. section 7.0 section 7.4.2
- Capacity: limit the number of entries to prevent unbounded growth. When full, one policy removes the oldest entry; updating an entry resets its position and timestamp. section 7.4 section 7.4.2
Evict the oldest entry
With capacity three, insert keys 1, 2, and 3, then update key 1. Adding key 4 removes key 2, because the update made key 1 newer. A slice tracks insertion order so updates and deletions can remove keys from the middle. section 7.4.2
Listing 7.20 cache.go: Upsert with the new helper functions
func (c *Cache[K, V]) Upsert(key K, value V) {
c.mu.Lock()
defer c.mu.Unlock()
_, alreadyPresent := c.data[key]
switch {
case alreadyPresent:
c.deleteKeyValue(key) #1
case len(c.data) == c.maxSize: #2
c.deleteKeyValue(c.chronologicalKeys[0])
}
c.addKeyValue(key, value) #3
}
The capacity-aware Upsert locks the cache, removes an existing or oldest entry as needed, and adds the new value. section 7.4.2






































