Documentation ¶
Index ¶
Examples ¶
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 holds a lazily initialized value of T. A non-zero lazy must not be copied after first use.
Lazy should be used where a single value is initialized and reset at different call sites with undefined order and values. A value initialized in one place and read many times should use sync.OnceValue instead.
Example ¶
var lazy Lazy[int] // the first invocation to lazy will be called and set the value fmt.Println(lazy.Get(func() int { return 42 })) // the second invocation will not call init again, using the first value fmt.Println(lazy.Get(func() int { return 43 })) // Set can be used to set a specific value lazy.Set(0) fmt.Println(lazy.Get(func() int { panic("never called") }))
Output: 42 42 0
Example (Nil) ¶
var lazy Lazy[int] // passing nil as the initialization function causes the zero value to be set fmt.Println(lazy.Get(nil))
Output: 0
func (*Lazy[T]) Get ¶
func (lazy *Lazy[T]) Get(init func() T) T
Get returns the value associated with this Lazy.
If no other call to Get has started or completed an initialization, calls init to initialize the value. A nil init function indicates to store the zero value of T. If an initialization has been previously completed, the previously stored value is returned.
If init panics, the initialization is considered to be completed. Future calls to Get() do not invoke init, and the zero value of T is returned.
Get may safely be called concurrently.