lazy

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 3 Imported by: ? modules, 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 lazy provides a generic thread-safe lazy initializer.

Lazy[T] ensures that an expensive initialization function runs exactly once, even under concurrent access. It uses atomic.Pointer for lock-free reads after successful initialization and singleflight.Group to deduplicate concurrent initialization attempts.

If initialization fails, the next Get call retries. There is no caching of failed attempts — every failure triggers a retry on the next access.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Lazy

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

Lazy is a thread-safe lazy initializer for type T. The zero value is not usable; use New to create instances.

func New

func New[T any](init func(ctx context.Context) (*T, error)) *Lazy[T]

New creates a Lazy that will call init on first Get. The init function should return a fully initialized T or an error. If init returns an error, it will be retried on the next Get call.

func (*Lazy[T]) Get

func (l *Lazy[T]) Get(ctx context.Context) (*T, error)

Get returns the initialized value, calling init on first access. Concurrent callers are deduplicated via singleflight — only one init runs at a time; others wait for the result.

func (*Lazy[T]) Loaded

func (l *Lazy[T]) Loaded() bool

Loaded reports whether the value has been successfully initialized. It does not trigger initialization.

Jump to

Keyboard shortcuts

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