lazyloading

package
v0.77.0 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2022 License: Apache-2.0 Imports: 3 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Func

func Func(init func() interface{}) func() interface{}

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

Example
package main

import (
	"fmt"

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

func main() {
	value := lazyloading.Func(func() interface{} {
		// my expensive calculation's result
		return 42
	})

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

Types

type Values

type Values struct {
	// contains filtered or unexported fields
}

func (*Values) Get

func (ll *Values) Get(key interface{}, init func() interface{}) interface{}

Get will return a value

type Var

type Var[T any] struct {
	// Init will set the constructor block for the variable's value
	Init func() (T, error)
	// contains filtered or unexported fields
}
Example
package main

import (
	"math/rand"

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

type MyStruct struct {
	lazyLoadedVar lazyloading.Var[int]
}

func (ms *MyStruct) Num() int {
	return ms.lazyLoadedVar.Do(func() int {
		return rand.Int()
	})
}

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

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

func (*Var[T]) Do

func (i *Var[T]) Do(init func() T) T

Do set the .Init block with the received block, and then immediately retrieve the value. However it will only set .Init once, to provide an easy to use syntax sugar to the lazyloading.Var.

When Var defined as a struct field, and used from the method of the struct with a pointer receiver, then it will streamline the lazy loading process for that struct field.

Example
package main

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

func main() {
	var v1 lazyloading.Var[int]

	_ = v1.Do(func() int {
		return 42
	})
}
Output:

func (*Var[T]) DoErr

func (i *Var[T]) DoErr(init func() (T, error)) (T, error)
Example
package main

import (
	"fmt"

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

func main() {
	var v1 lazyloading.Var[int]

	_, err := v1.DoErr(func() (int, error) {
		return 0, fmt.Errorf("boom")
	})

	fmt.Println(err)
}
Output:

func (*Var[T]) Value

func (i *Var[T]) Value() (T, error)
Example
package main

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

func main() {
	var v1 = lazyloading.Var[int]{Init: func() (int, error) {
		return 42, nil
	}}

	_, _ = v1.Value() // returns with the result
}
Output:

Jump to

Keyboard shortcuts

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