A re-implementation and drop-in replacement of the standard Go (Golang) sync.Once
, with added support for return values (using generics)! This package exports three additional Once
-like primitives, in addition to the standard once.Once
:
once.Error
returns an error value
Do(f func() error) error
once.Value[T]
returns a value
Do(f func() T) T
once.ValueError[T]
returns a (value, error) tuple
Do(f func() (T, error)) (T, error)
These three primitives have the behavior that, like with the standard Once
, the function passed is ever only executed once. However, they also return the value returned by that one execution to all subsequent callers.
var o once.ValueError[string]
val, err := o.Do(func() (string, error) {
return "Hello!", nil
})
if err != nil {
// Do something
}
fmt.Println(val) // prints "Hello!"