Table of Contents

sync.Once

What is it?

`sync.Once` ensures that a function is executed only once, even when called by multiple goroutines concurrently.

What is it used for?

When to use

Example

package main
 
import (
    "fmt"
    "sync"
)
 
var once sync.Once
var value string
 
func initValue() {
    value = "initialized"
}
 
func GetValue() string {
    once.Do(initValue)
    return value
}
 
func main() {
    fmt.Println(GetValue())
}

Notes / pitfalls

Hard words (English)