Menu

1 / 4

sync.OnceFunc, OnceValue, OnceValues: When Each Beats sync.Once

DEV Community·Gabriel Anhaia·6 months ago
#LC3Cy0Cn
#concurrency#go#stdlib#once#sync
Reading 0:00
15s threshold

Book: Complete Guide to Go Programming

Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go

My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools

Me: xgabriel.com | GitHub

Open any Go codebase past a year old and you will hit this pattern:

var ( cfgOnce sync . Once cfg * Config cfgErr error )

func GetConfig () ( * Config , error ) { cfgOnce . Do ( func () { cfg , cfgErr = loadConfig () }) return cfg , cfgErr }

Enter fullscreen mode

Exit fullscreen mode

Three package-level variables. A closure that mutates two of them by name. A function that reads them after Do returns. It works. It has worked since Go 1.0.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.