Documentation ¶
Overview ¶
Package once provides a simple way to do something exactly once.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Func ¶
func Func(f func()) func()
Func returns a function that invokes f only once. The returned function may be called concurrently.
If f panics, the returned function will panic with the same value on every call.
Types ¶
type FuncMap ¶
FuncMap is a map of functions that are only computed once.
func (*FuncMap[K]) Delete ¶
func (m *FuncMap[K]) Delete(key K)
Delete deletes the key and its function from the map.
type LazyValueMap ¶
type LazyValueMap[K, V any] struct { New func(key K) V // contains filtered or unexported fields }
LazyValueMap initializes values when they are first accessed.
Example ¶
package main import ( "fmt" "go.nhat.io/once" ) func main() { type Person struct { ID string Name string } people := once.LazyValueMap[string, *Person]{ New: func(key string) *Person { return &Person{ID: key} }, } instance1 := people.Get("1") instance2 := people.Get("1") fmt.Println(instance2.Name) instance1.Name = "John Doe" fmt.Println(instance2.Name) }
Output: John Doe
func (*LazyValueMap[K, V]) Delete ¶
func (p *LazyValueMap[K, V]) Delete(key K)
Delete removes the key and its value from the map.
func (*LazyValueMap[K, V]) Get ¶
func (p *LazyValueMap[K, V]) Get(key K) V
Get returns the value for key if it exists. Otherwise, it calls New and stores.
func (*LazyValueMap[K, V]) Len ¶
func (p *LazyValueMap[K, V]) Len() int
Len returns the number of entries in the map.
type Map ¶
Map is simpler version of sync.Map.
func (*Map[K, V]) Delete ¶
func (m *Map[K, V]) Delete(key K)
Delete removes the key and its value from the map.
type Once ¶
Once is an object that will perform exactly one action.
A Once must not be copied after first use.
In the terminology of the Go memory model, the return from f “synchronizes before” the return from any call of once.Do(f).
type ValueMap ¶
ValueMap is a map of functions that are only computed once.
func (*ValueMap[K, V]) Delete ¶
func (m *ValueMap[K, V]) Delete(key K)
Delete removes the key and its function from the map.
func (*ValueMap[K, V]) Do ¶
func (m *ValueMap[K, V]) Do(key K, f func() V) V
Do executes the function only once for the given key and returns the value returned by f.
If f panics, the function will panic with the same value on every call.
type ValuesMap ¶
ValuesMap is a map of functions that are only computed once.
func (*ValuesMap[K, V1, V2]) Delete ¶
func (m *ValuesMap[K, V1, V2]) Delete(key K)
Delete removes the key and its function from the map.