A generic, thread-safe LRU (least-recently-used) cache for Go, with
optional per-entry TTL (time-to-live) expiration. Zero third-party
dependencies — built entirely on the Go standard library, using Go
generics (container/list for O(1)-ish LRU ordering) and
sync.Mutex for safe concurrent access.
go get github.com/kasapdev/go-cachepackage main
import (
"fmt"
"time"
"github.com/kasapdev/go-cache"
)
func main() {
// A cache of string keys to int values, holding at most 2 entries.
c := cache.New[string, int](2)
c.Put("a", 1)
c.Put("b", 2)
// A TTL variant: this entry expires after 50ms.
c.PutWithTTL("temp", 99, 50*time.Millisecond)
if v, ok := c.Get("a"); ok {
fmt.Println("a =", v)
}
// Inserting a third key evicts the least-recently-used entry.
c.Put("c", 3)
if _, ok := c.Get("b"); !ok {
fmt.Println("b was evicted")
}
c.Delete("c")
hits, misses := c.Stats()
fmt.Printf("hits=%d misses=%d len=%d\n", hits, misses, c.Len())
}Creates a new cache with the given capacity, backed by the real system clock. Capacity values less than 1 are treated as 1.
Creates a new cache with an explicit Clock implementation, primarily
useful for tests that need to control "now" without sleeping.
Abstracts the current time. New uses a default implementation backed
by time.Now; supply your own (e.g. a fake clock) via NewWithClock.
Returns the value for key and true if present and not expired.
On a hit, the entry becomes the most-recently-used entry. Returns the
zero value of V and false on a miss or if the entry has expired
(an expired entry is evicted as part of the lookup).
Inserts or updates key with value, with no expiration. Marks the
entry as most-recently-used. Evicts the least-recently-used entry if
the cache is over capacity afterward.
Same as Put, but the entry expires after ttl elapses (as measured
by the cache's Clock). A ttl of 0 or less means "never expires".
Removes key from the cache, if present. No-op otherwise.
Looks up key without side effects: it does not refresh the entry's
recency, does not count toward Stats, and does not evict an expired entry
(an expired entry is reported as absent). Useful for inspection where a read
must not change which entry is evicted next.
Returns the keys of all live (non-expired) entries from most- to
least-recently-used, as a copy. Like Peek, it has no side effects.
Removes every entry. Capacity and the Stats counters are unchanged.
Returns the number of entries currently stored, including any whose
TTL has passed but hasn't yet been purged by a Get call. This keeps
Len an O(1) operation rather than a full scan; call Get on a
specific key if you need to know whether it is actually still live.
Returns the cumulative number of Get hits and misses since the
cache was created. These counters are never reset automatically.
go test ./...To also run with the race detector (as CI does):
go test ./... -race -vMIT — see LICENSE.