lazyinit

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: May 1, 2025 License: LGPL-2.1 Imports: 2 Imported by: 0

README

lazyinit

Go Reference Go Report Card GitHub License

Thread-safe, generic lazy initialization in Go for efficiently managing expensive resources concurrently.

Overview

Often, you have resources or values that are expensive to create (e.g., database connections, loaded configuration files, complex computed objects) and you only want to incur that cost when the value is actually needed for the first time. lazyinit handles the synchronization logic required to make this process safe and efficient in concurrent Go programs.

Features

  • Thread-Safe: Uses mutexes and atomic operations to safely handle concurrent calls to Get() and Reset().
  • Lazy Initialization: The initialization logic runs only when Get() is called for the first time (or after a Reset()).
  • Generics: Fully utilizes Go 1.18+ generics ([T any]) for type safety without needing interface{}.
  • Flexible Initialization: Supports initialization with:
    • An already computed value (New).
    • A zero-argument function (NewFromFunc).
    • A function accepting arguments (NewFromFuncWithArgs).
  • Resettable: Allows clearing the cached value to force re-initialization on the next Get() call.
  • Initialization Check: Provides IsInitialized() to check the status without triggering initialization.
  • Zero External Dependencies: Uses only the Go standard library.

Installation

Use go get -u command:

go get -u github.com/colduction/lazyinit-go

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type LazyInit

type LazyInit[T any] interface {
	// Get retrieves the lazily initialized value.
	Get(args ...any) T
	// Reset clears the initialized value.
	Reset()
	// IsInitialized checks if the value has been initialized.
	IsInitialized() bool
}

LazyInit is an interface for lazily initializing a value of type T.

func New

func New[T any](val T) LazyInit[T]

New creates a new LazyInit instance with an already initialized value.

func NewFromFunc

func NewFromFunc[T any](initFn func() T) LazyInit[T]

NewFromFunc creates a new LazyInit instance with a no-argument initialization function.

func NewFromFuncWithArgs

func NewFromFuncWithArgs[T any](initFn func(args ...any) T) LazyInit[T]

NewFromFuncWithArgs creates a new LazyInit instance with an initialization function accepting arguments.

Jump to

Keyboard shortcuts

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