memoize

package
v1.164.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 3 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package memoize caches the results of expensive function calls, keyed by string, with an optional time-to-live. Concurrent calls for the same key are de-duplicated so the underlying function runs only once at a time.

A failed call (one that returns a non-nil error) is never cached, so the next call retries. A panic in the memoized function is propagated to every caller waiting on the same key (the value is wrapped and re-raised by the underlying golang.org/x/sync/singleflight group).

Expired entries are evicted lazily, when their key is next accessed or overwritten; there is no background janitor. Memory use is therefore bounded by the number of distinct keys, which suits callers that memoize a small, fixed set of keys.

Index

Constants

View Source
const NoExpiration time.Duration = -1

NoExpiration, used as the ttl passed to New, keeps cached values forever. Any ttl <= 0 has the same effect.

Variables

This section is empty.

Functions

This section is empty.

Types

type Memoizer

type Memoizer[T any] struct {
	// contains filtered or unexported fields
}

Memoizer caches values of type T keyed by string. The zero value is not usable; create one with New. A Memoizer is safe for concurrent use by multiple goroutines.

func New

func New[T any](ttl time.Duration) *Memoizer[T]

New creates a Memoizer whose cached values expire after ttl. A ttl <= 0 (for example NoExpiration) keeps values forever.

func (*Memoizer[T]) Memoize

func (m *Memoizer[T]) Memoize(key string, fn func() (T, error)) (T, error)

Memoize returns the cached value for key, computing it with fn on a miss or when the cached value has expired. Only one execution of fn is in-flight for a given key at a time; concurrent callers share its result. If fn returns an error, the result is not cached and the error is returned to the caller(s).

Jump to

Keyboard shortcuts

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