Skip to content

Instantly share code, notes, and snippets.

@koonix
Created September 27, 2024 23:04
Show Gist options
  • Save koonix/8d963959e4f22da2f6b934a810772d54 to your computer and use it in GitHub Desktop.
Save koonix/8d963959e4f22da2f6b934a810772d54 to your computer and use it in GitHub Desktop.
Go object that stores a value only once
package once
import "sync"
type Once[T any] struct {
sync.Mutex
has bool
v T
}
func (o *Once[T]) Store(v T) {
o.Lock()
defer o.Unlock()
if o.has {
return
}
o.v = v
o.has = true
}
func (o *Once[T]) Load() T {
o.Lock()
defer o.Unlock()
return o.v
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment