typestar

sync.Once in Go

Exactly-once initialization, safe from any number of goroutines.

var (
    setupOnce sync.Once
    table     map[string]int
)

func lookup(key string) int {
    setupOnce.Do(func() {
        table = map[string]int{"basics": 39, "traits": 19}
    })
    return table[key]
}

var expensive = sync.OnceValue(func() int {
    return 40 + 2
})

func answer() int { return expensive() }

How it works

  1. Do runs the function the first time and never again.
  2. Later callers block until that first run finishes.
  3. OnceValue is the newer form that returns the result.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
283
Tokens
82
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 47 seconds.

Type this snippet

Step 3 of 5 in Synchronization, step 16 of 25 in Concurrency.

← Previous Next →