What is new in Go 1.21?
In this section, we are going to talk about two new features that came with Go 1.21: The sync.OnceFunc()
function of the standard library and the built-in function clear
, which deletes or zeroes out all elements of a map, a slice, or a type parameter type.
We are going to begin with the sync.OnceFunc()
function.
The sync.OnceFunc() function
The sync.OnceFunc()
function is a helper function of the sync
package. Its full signature is func OnceFunc(f func()) func()
, which means that it accepts a function as a parameter and returns another function. In more detail, sync.OnceFunc()
returns a function that invokes function f
only once—the important detail here is the only once.
This might look unclear now but the presented code, which is saved as syncOnce.go
, is going to shed some light on the use of sync.OnceFunc()
. The code of syncOnce.go
is presented in two parts. The first part is the following:
package main
import (
"fmt...