lazyload

package
v0.166.2 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2023 License: Apache-2.0 Imports: 1 Imported by: 0

Documentation

Overview

Package lazyload DEPRECATED: use zerokit instead

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Make

func Make[T any](init func() T) func() T

Make allows a value to be lazy evaluated when it is actually used.

Example
package main

import (
	"fmt"

	"github.com/adamluzsi/frameless/pkg/lazyload"
)

func main() {
	value := lazyload.Make(func() int {
		// my expensive calculation's result
		return 42
	})

	// one eternity later
	fmt.Println(value())
	fmt.Println(value())
}
Output:

Types

type Var

type Var[T any] struct {
	Init func() T
	// contains filtered or unexported fields
}
Example (AsStructField)
package main

import (
	"math/rand"

	"github.com/adamluzsi/frameless/pkg/lazyload"
)

type MyStruct struct {
	lazyLoadedVariable lazyload.Var[int]
}

func (ms *MyStruct) Num() int {
	return ms.lazyLoadedVariable.Get(func() int {
		return rand.Int()
	})
}

func main() {
	ms := &MyStruct{}

	ms.Num() // uses lazy loading under the hood
}
Output:

func (*Var[T]) Get

func (i *Var[T]) Get(inits ...func() T) T
Example
package main

import (
	"github.com/adamluzsi/frameless/pkg/lazyload"
)

func main() {
	myInt := lazyload.Var[int]{
		Init: func() int {
			return 42
		},
	}
	_ = myInt.Get() // get 42
}
Output:

Example (WithInitBlock)
package main

import (
	"github.com/adamluzsi/frameless/pkg/lazyload"
)

func main() {
	// This use-case is ideal for initializing lazyload.Var s in struct fields,
	// where defining Init at high level is not possible.
	type MyStruct struct {
		myInt lazyload.Var[int]
	}

	r := &MyStruct{}
	// func (r *MyType) getValue() int {
	getValue := func() int {
		return r.myInt.Get(func() int {
			return 42
		})
	}

	_ = getValue() // 42
}
Output:

func (*Var[T]) Reset added in v0.115.0

func (i *Var[T]) Reset()

func (*Var[T]) Set

func (i *Var[T]) Set(v T)

Jump to

Keyboard shortcuts

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