Junior — Middle
Kas kasutasite funktsiooni Once Go keeles ja kuidas te seda oma projektides kasutasite?
sobes.tech AI
Vastus AI-lt
In the Go language, the sync.Once function is used to ensure that a certain piece of code is executed exactly once, even if the call is made simultaneously from multiple goroutines. This is useful, for example, for initializing resources that should only be created once.
Example of usage:
var once sync.Once
func initialize() {
fmt.Println("Initialization complete")
}
func main() {
for i := 0; i < 5; i++ {
go func() {
once.Do(initialize) // initialize will be called only once
}()
}
time.Sleep(time.Second) // Wait for goroutines to finish
}
In my projects, I have used sync.Once for lazy initialization of configuration or database connection to avoid repeated initializations and race conditions.