Reliability and safety
oncepolicy
Checks sync.Once function wrappers that are immediately discarded.
What it detects
sync.OnceFunc, sync.OnceValue, and sync.OnceValues preserve their state in
the function value they return. Store that wrapper instead of constructing,
calling, and discarding it in one expression.
Checks
| Check | What it detects |
|---|---|
discarded-wrapper |
Reports sync.Once function wrappers that are called and immediately discarded. |
Why this is flagged
Each newly created wrapper has fresh once-only state. Recreating it at every
call means the wrapped work can run repeatedly, defeating the guarantee that
made sync.Once useful in the first place.
Further reading: sync.OnceFunc.
How to fix it
Create the wrapper once and store the returned function in a variable or field that lives across calls. Call that stored function whenever the once-only value or action is needed.
Examples
Flagged code
func start() { // gohawk: sync.OnceFunc wrapper is discarded after one call sync.OnceFunc(initialize)()}Accepted code
func startOnce() { initializeOnce()}