Go init() Function 🎯

beginner
11 min

Go init() Function 🎯

Welcome to our deep dive into the init() function in Go (Golang)! This function is a special part of Go's programming language that allows you to perform certain actions before your main program starts executing. Let's explore its world together! 🌎

What is the init() Function? 📝

In Go, the init() function is a non-standard function, meaning it's not part of Go's predefined functions. It is called automatically before the main() function when your program starts. The init() function can be defined multiple times within the same package, but each init() function must have a unique name.

Why use the init() Function? 💡

The init() function is useful when you need to initialize variables or perform certain actions before the main() function starts executing. For example, initializing global variables, loading configuration files, or setting up database connections.

The Structure of the init() Function 📝

The init() function has no return type and no parameters. It is defined within the package scope, and it's automatically called before the main() function starts.

go
package main import "fmt" func init() { fmt.Println("Initializing global variables...") // Your initialization code here } func main() { // Your main function code here }

💡 Pro Tip:

You can define multiple init() functions within the same package, but they must have unique names. Each init() function will be called in the order they are defined in the source code.

Practical Example 🎯

Let's create a simple example where we initialize a global variable in the init() function and use it in the main() function.

go
package main import "fmt" var globalVar string func init() { globalVar = "Hello, Go!" fmt.Println("Initializing global variable...") } func main() { fmt.Println(globalVar) }

When you run this program, it will first print "Initializing global variable..." and then print "Hello, Go!".

Quiz 📝

Question: What is the purpose of the init() function in Go?

A: To define standard functions B: To perform actions before the main() function starts C: To initialize local variables

Correct: B

Explanation: The init() function is used to perform certain actions before the main() function starts executing.