Go Q & A

 

What is the purpose of the init function in Go?

In Go, the init function is a special function that is automatically called by the Go runtime before the program’s main function is executed. The init function is typically used for package initialization tasks, such as setting up global variables, initializing data structures, or registering dependencies.

 

Each package in a Go program can have one or more init functions, and they are executed in the order in which they are declared within the package file. The init function cannot be called explicitly, and it is executed exactly once per package, regardless of how many times the package is imported.

 

Here’s an example of using the init function in a Go package:

go

package main

import (
    "fmt"
)

var message string

func init() {
    message = "Hello, world!"
}

func main() {
    fmt.Println(message)
}

In this example, the init function initializes the message variable with the string “Hello, world!” before the main function is executed. The main function then prints the value of the message variable to the console.

 

The init function is a convenient way to perform package-level initialization tasks in Go and ensure that they are executed before the program starts executing its main logic.

Previously at
Flag Argentina
Mexico
time icon
GMT-6
Over 5 years of experience in Golang. Led the design and implementation of a distributed system and platform for building conversational chatbots.