Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Member-only story

Go Programming | Instantiating A Singleton Object

Jerry An
Level Up Coding
Published in
2 min readMay 10, 2022

--

Photo by Simon Berger on Unsplash

Instantiating a singleton object is a way to ensure that only one instance of a class is created.

I will demonstrate different ways to instantiate a singleton object in this post.

1. Package Level Variable

Variable defined in a package scope is accessible to all the files in the same package. It is helpful to share data between different functions.

We can create a singleton object by assigning a value to a variable in the package scope.

For example:

“abc.go”

package abcimport "time"var StartTime = time.Now()

“main.go”

package mainimport (
"fmt"
"time"
"example.com/m/abc"
)
func main() {
fmt.Println(abc.StartTime)
time.Sleep(1 * time.Second)
fmt.Println(abc.StartTime)
}

“result”:

2022-05-10 11:58:06.076867 +0800 CST m=+0.000095853
2022-05-10 11:58:06.076867 +0800 CST m=+0.000095853

As our expectation, the singleton objectStartTime is the same in two consecutive calls.

2. init function

The functioninit is a predefined function that is called when the package is imported. It is typically used to initialize a specific state of the package.

“abc.go”

package abcimport "time"var StartTime time.Time
func init() {
StartTime = time.Now()
}

3. A function call from in the Main function

At the start of the main function, we call the initApp function to initialize some variables.

“main.go”

package mainimport (
"fmt"
"time"
)
var startTime time.Timefunc initApp() {
startTime = time.Now()
}
func main() {
initApp()

fmt.Println(startTime)
}

--

--

Responses (1)

Write a response