Created
September 27, 2024 23:04
-
-
Save koonix/8d963959e4f22da2f6b934a810772d54 to your computer and use it in GitHub Desktop.
Go object that stores a value only once
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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