Standard library / sync
sync.OnceFunc()
Wrap a callback so concurrent callers invoke it only once. If it panics, later calls panic with the same value. Expected stdout: '1\n'.
Formal Syntax & Structure
go syntaxgo
func OnceFunc(f func()) func()Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| f | func() | Function to invoke; see callback timing and concurrency rules. |
Return Value
func()
Concurrent-safe function that runs the callback at most once.
Working Example
Example Snippetgo
package main
import ( "fmt" "sync")
func main() { n := 0; f := sync.OnceFunc(func() { n++ }); f(); f(); fmt.Println(n) }