This example shows us how we can do something only once even if we call it many times. Such behaviour is useful when it comes to avoid wasting system resources and many more.


Example


As you can see below, it will print Loaded only once although we call the function three times.


package pkg

import (
"fmt"
"sync"
)

var o sync.Once

func LoadConfig() {
fmt.Println("Begin")

o.Do(func() {
fmt.Println("Load")
})

fmt.Println("End")
}

package main

import (
"github.com/inanzzz/football/internal/pkg"
}

func main() {
pkg.LoadConfig()
pkg.LoadConfig()
pkg.LoadConfig()
}

Result


Begin
Loaded
End
Begin
End
Begin
End