https://github.com/hsson/once
Drop-in replacement for Go's sync.Once with added features for returning values
https://github.com/hsson/once
mutex once-do sync synchronization
Last synced: about 1 year ago
JSON representation
Drop-in replacement for Go's sync.Once with added features for returning values
- Host: GitHub
- URL: https://github.com/hsson/once
- Owner: hsson
- License: bsd-3-clause
- Created: 2020-12-05T23:39:30.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2022-10-25T16:05:14.000Z (over 3 years ago)
- Last Synced: 2025-03-25T05:05:25.776Z (over 1 year ago)
- Topics: mutex, once-do, sync, synchronization
- Language: Go
- Homepage:
- Size: 6.84 KB
- Stars: 8
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# hsson/once
[](https://pkg.go.dev/github.com/hsson/once) [](https://goreportcard.com/report/github.com/hsson/once)
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
```go
Do(f func() error) error
```
`once.Value[T]` returns a value
```go
Do(f func() T) T
```
`once.ValueError[T]` returns a (value, error) tuple
```go
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
```go
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!"
```