Sync Once Panic Marks Init Done
A panic inside sync.Once.Do still marks the Once done, so later calls skip the init and a failed initialization is never retried.
Code
package main
import (
"fmt"
"sync"
)
func main() {
var once sync.Once
var calls int
// a panic mid-init: Do considers f already run and never retries it
runInit := func() {
calls++
panic("config source unavailable")
}
func() {
defer func() {
if r := recover(); r != nil {
fmt.Println("first Do panicked:", r)
}
}()
once.Do(runInit)
}()
// the second call returns immediately: done is already marked while init is still missing
once.Do(runInit)
fmt.Println("init attempts:", calls)
}What the code does
The plain reading: it comes down to the function main, doing all the work.
Cleanup is attached with defer, so it runs on every exit path of the function.
What to watch for
- The runtime is the only requirement — no packages, no install.
Applying it
Signature: func main()
The run emits 2 labeled sections — first Do panicked:, init attempts: — one per step.
Statements that carry the weight
if r := recover(); r != nil {
fmt.Println("first Do panicked:", r)
}
panic("config source unavailable")
var once sync.Once
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Sync Once Panic Marks Init Done print when run?
- Run it as a complete program — the output lines carry labels such as `first Do panicked:`, `init attempts:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.