Skip to content

hsson/once

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

hsson/once

PkgGoDev GoReportCard

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.

Example usage

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!"

About

Drop-in replacement for Go's sync.Once with added features for returning values

Topics

Resources

License

Stars

Watchers

Forks

Languages