An expiration date is the timestamp after which a cached value is too outdated to trust. A time to live (TTL) determines that timestamp for each stored entry. section 7.0 section 7.4.1
A TTL-based cache applies expiration through a small set of operations:
- Store each value with an expires timestamp calculated from the current time plus the configured TTL. section 7.4.1
- Require the TTL when constructing the cache, allowing different caches to suit rapidly changing or stable values. section 7.4.1
- Check expiration during Read; delete an expired entry and report it as absent, without exposing the reason to the caller. section 7.4.1
- Leave Delete behavior unchanged and replace both the value and expiration timestamp when Upsert updates an entry. section 7.4.1
Testing expiration
Create a string cache with a 100-millisecond TTL, insert "Norwegian" → "Blue", verify an immediate read succeeds, wait 200 milliseconds, then verify the read returns an empty value and found=false.
Listing 7.14 cache.go: Read with a TTL
func (c *Cache[K, V]) Read(key K) (V, bool) {
c.mu.Lock()
defer c.mu.Unlock()
var zeroV V #1
e, ok := c.data[key]
switch {
case !ok:
return zeroV, false
case e.expires.Before(time.Now()):
// The value has expired.
delete(c.data, key)
return zeroV, false
default:
return e.value, true
}
}
Inspect the complete Read implementation that distinguishes missing entries, expired entries, and valid entries. section 7.4.1



