Help us shape the future of Go! Take the 2026 Go Developer Survey

lru

package
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2026 License: GPL-3.0 Imports: 2 Imported by: 0

Documentation

Overview

Package lru provides a least-recently-used cache bounded by entry count and total cost.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Cache is an LRU map. It is not safe for concurrent use; callers guard it with the lock that protects their related state.

func New

func New[K comparable, V any](o Options[K, V]) *Cache[K, V]

New returns an empty cache.

func (*Cache[K, V]) Add

func (c *Cache[K, V]) Add(key K, val V) bool

Add stores val as the most recently used entry for key, then evicts least-recently-used entries until both bounds hold. A value whose cost alone exceeds MaxCost is not stored, and any previous value is removed; Add reports whether val was stored.

func (*Cache[K, V]) All

func (c *Cache[K, V]) All() iter.Seq2[K, V]

All yields the entries from most to least recently used without changing their recency. The cache must not be modified during iteration.

func (*Cache[K, V]) Clear

func (c *Cache[K, V]) Clear()

Clear deletes every entry.

func (*Cache[K, V]) Contains

func (c *Cache[K, V]) Contains(key K) bool

Contains reports whether key is cached, without changing its recency.

func (*Cache[K, V]) Cost

func (c *Cache[K, V]) Cost() int64

Cost returns the total cost of the entries.

func (*Cache[K, V]) Get

func (c *Cache[K, V]) Get(key K) (V, bool)

Get returns key's value and marks it most recently used.

func (*Cache[K, V]) Len

func (c *Cache[K, V]) Len() int

Len returns the number of entries.

func (*Cache[K, V]) Oldest

func (c *Cache[K, V]) Oldest() (K, V, bool)

Oldest returns the least recently used entry.

func (*Cache[K, V]) Peek

func (c *Cache[K, V]) Peek(key K) (V, bool)

Peek returns key's value without changing its recency.

func (*Cache[K, V]) Remove

func (c *Cache[K, V]) Remove(key K) bool

Remove deletes key and reports whether it was cached.

func (*Cache[K, V]) RemoveFunc

func (c *Cache[K, V]) RemoveFunc(drop func(K, V) bool) int

RemoveFunc deletes every entry for which drop returns true, visiting from least to most recently used, and returns how many it deleted.

type Options

type Options[K comparable, V any] struct {
	MaxEntries int
	MaxCost    int64
	// Cost weighs an entry against MaxCost; nil weighs every entry 0.
	Cost func(K, V) int64
	// OnEvict is called for each entry removed to satisfy a bound, never
	// for Remove, RemoveFunc, Clear or a replaced value.
	OnEvict func(K, V)
}

Options bound a Cache. A zero bound is unlimited.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL