Fallible Lazy Init With sync.OnceValues

Run a fallible initializer exactly once across concurrent callers with sync.OnceValues, so every caller receives the same value or the same error.

GoConfig Management

Code

gosnippet
40 lines
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

var calls atomic.Int32

type Config struct {
	Region string
	Limit  int
}

func loadConfig() (*Config, error) {
	calls.Add(1)
	return &Config{Region: "us-east-1", Limit: 100}, nil
}

func main() {
	// OnceValues 包装可失败初始化:无论多少调用者,函数体只执行一次
	load := sync.OnceValues(loadConfig)

	var wg sync.WaitGroup
	for i := 0; i < 4; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			cfg, err := load()
			if err != nil {
				fmt.Println("load error:", err)
				return
			}
			fmt.Println("got config:", cfg.Region, cfg.Limit)
		}()
	}
	wg.Wait()
	fmt.Println("loader ran", calls.Load(), "time(s)")
}

Inside the snippet

Count the functions loadConfig and main as the entire surface area of Fallible Lazy Init With sync.OnceValues.

for i := 0; i < 4; i++ is the loop that carries the per-item work. Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly. The task is handed to a goroutine and runs concurrently. Deferred at entry, executed at exit: defer keeps cleanup adjacent to acquisition.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.
  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Putting it to use

Entry signature: func loadConfig() (*Config, error)

Labeled lines are what you get — load error:, got config:, loader ran — when the file runs.

Core lines

return &Config{Region: "us-east-1", Limit: 100}, nil
if err != nil {
fmt.Println("load error:", err)
return
}
load := sync.OnceValues(loadConfig)

Interactive Tools for This Topic

FAQ

How do errors reach the caller?
The Go way: `err` comes back from each call, and 1 checkpoint here test it before proceeding.
What does Fallible Lazy Init With sync.OnceValues print when run?
No setup needed: run the file and look for labeled lines like `load error:`, `got config:`, `loader ran` in the output.