lazy

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2023 License: MIT Imports: 1 Imported by: 0

README

Lazy

A lazy value loader, it can be used to load expensive computation only when it is needed and cache the result for future use.

Installation

go get github.com/asmsh/lazy

Example

package main

import (
	"bytes"
	"fmt"
	"sync"
	"text/template"

	"github.com/asmsh/lazy"
)

var helloTmpl = lazy.NewValue(func() (*template.Template, error) {
	tmplTxt := `Hello {{.}}!`
	tmpl := template.Must(template.New("hello").Parse(tmplTxt))
	return tmpl, nil
})

func main() {
	users := []string{
		"UserA",
		"UserB",
		"UserC",
	}

	wg := sync.WaitGroup{}
	wg.Add(len(users))

	for _, v := range users {
		user := v

		go func() {
			defer wg.Done()

			b := bytes.Buffer{}
			helloTmpl.Val().Execute(&b, user)
			fmt.Println(b.String())
		}()
	}

	wg.Wait()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Value

type Value[T any] interface {
	// Val returns the lazily-loaded value contained within this Value.
	// It will load the value if it wasn't loaded yet.
	// All callers will block until the value is loaded.
	Val() T

	// Err returns the error that occurred while loading the value.
	// It will load the value if it wasn't loaded yet.
	// All callers will block until the value is loaded.
	Err() error
	// contains filtered or unexported methods
}

Value is a generic container offering lazy-loading for values of any type. Safe for concurrent usage.

func NewValue

func NewValue[T any](init func() (T, error)) Value[T]

NewValue creates a new Value, which will be lazily-loaded from the loader function provided, init, upon first call to any of its methods.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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