mdawar.dev

A blog about programming, Web development, Open Source, Linux and DevOps.

Go - Package Initialization

(Updated: )

The init Function

The init function is a special function in Go:

  • It is executed automatically when a package is imported
  • It is used to initialize global variables, perform setup tasks and register any cleanup routines
  • A package can have multiple init functions that will be executed in the order they are defined in
go
package main

import "fmt"

var message string

func init() {
  // Set the value of the global variable.
  message = "Hello, world!"
}

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

Alternative

A better readable alternative to the init function to do initialization in a package, is to use an explicit function call to initialize a variable.

go
package main

import "fmt"

var message = initialize()

// An example to show an alternative way of doing initialization in a package.
// This way of doing initialization is useful in packages other than `main`.
func initialize() string {
  return "Hello, world!"
}

func main() {
  // In the `main` package, initialization can instead be done
  // at the start of the `main` function.
  fmt.Println(message)
}