Standard library / sync

sync.OnceValue()

Cache the result of a single computation; concurrent calls share the result. A panic is repeated on later calls. Expected stdout: '7 7 1\n'.

Formal Syntax & Structure

go syntaxgo
func OnceValue[T any](f func() T) func() T

Parameters & Attributes

NameTypeDescription
ffunc() TFunction to invoke; see callback timing and concurrency rules.

Return Value

func() T

Function returning the cached value of type T.

Working Example

Example Snippetgo
package main
import (  "fmt"  "sync")
func main() { n := 0; f := sync.OnceValue(func() int { n++; return 7 }); fmt.Println(f(), f(), n) }
Go Reference