Main and init function


In Go, both the main function and the init function play important roles in the execution of a program. They serve different purposes and are executed at different stages of the program’s lifecycle.

  1. main Function:
    • The main function is the entry point of a Go program. It is mandatory for every executable program in Go.
    • When you run a Go executable, the program starts executing from the main function.
    • The main function does not take any arguments and does not return any value.

Example of a main function:

package main

import "fmt"

func main() {
    fmt.Println("Hello, Go!")
}
  1. init Function:
    • The init function is a special function that is automatically executed before the main function.
    • Each package can have multiple init functions, and they are executed in the order in which they are imported.
    • The init function is often used for package-level initialization, such as setting up global variables, configuring resources, or performing setup tasks.

Example of an init function:

package main

import "fmt"

func init() {
    fmt.Println("Initializing the program...")
}

func main() {
    fmt.Println("Hello, Go!")
}

In this example, the init function is executed before the main function, and it prints a message indicating the initialization process.

Both the main and init functions are essential components of Go programs. The init function provides a way to perform package-level setup tasks, and the main function serves as the starting point of execution for the program.

Here’s another example that demonstrates the use of both the init and main functions:

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func init() {
	rand.Seed(time.Now().UnixNano())
	fmt.Println("Initializing random number generator...")
}

func main() {
	randomNumber := generateRandomNumber()
	fmt.Println("Random Number:", randomNumber)
}

func generateRandomNumber() int {
	return rand.Intn(100)
}

In this example, we’re using the init function to initialize the random number generator from the math/rand package. This ensures that the random numbers generated are truly random by seeding the generator with the current time’s Unix nanoseconds.

The main function then calls the generateRandomNumber function to get a random number between 0 and 99 and prints it.

Remember that the init function is executed before the main function, and it’s a good place to put package-level setup and initialization tasks, as shown in this example.