Source File
oncefunc.go
Belonging Package
sync
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sync
// OnceFunc returns a function that invokes f only once. The returned function
// may be called concurrently.
//
// If f panics, the returned function will panic with the same value on every call.
func ( func()) func() {
var (
Once
bool
any
)
// Construct the inner closure just once to reduce costs on the fast path.
:= func() {
defer func() {
= recover()
if ! {
// Re-panic immediately so on the first call the user gets a
// complete stack trace into f.
panic()
}
}()
()
= nil // Do not keep f alive after invoking it.
= true // Set only if f does not panic.
}
return func() {
.Do()
if ! {
panic()
}
}
}
// OnceValue returns a function that invokes f only once and returns the value
// returned by f. The returned function may be called concurrently.
//
// If f panics, the returned function will panic with the same value on every call.
func [ any]( func() ) func() {
var (
Once
bool
any
)
:= func() {
defer func() {
= recover()
if ! {
panic()
}
}()
= ()
= nil
= true
}
return func() {
.Do()
if ! {
panic()
}
return
}
}
// OnceValues returns a function that invokes f only once and returns the values
// returned by f. The returned function may be called concurrently.
//
// If f panics, the returned function will panic with the same value on every call.
func [, any]( func() (, )) func() (, ) {
var (
Once
bool
any
)
:= func() {
defer func() {
= recover()
if ! {
panic()
}
}()
, = ()
= nil
= true
}
return func() (, ) {
.Do()
if ! {
panic()
}
return ,
}
}
The pages are generated with Golds v0.6.9-preview. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds. |