« Back to Index

Go: understanding init functions

View original Gist on GitHub

Tags: #go

main.go

// This is a file designed to be run on go.dev/play (link below).
// It validates the behaviour of init() functions.
// i.e. init() is only called once regardless of how many times its package is imported.
// https://go.dev/play/p/99YpDma6mVJ
package main

import (
	"play.ground/bar"
	"play.ground/foo"
)

func main() {
	foo.Message()
	bar.Message()
}
-- go.mod --
module play.ground
-- foo/foo.go --
package foo

import (
	"fmt"

	"play.ground/bar"
)

func Message() {
	fmt.Println("This is the foo package")
	bar.Message()
}
-- bar/bar.go --
package bar

import "fmt"

func init() {
	fmt.Println("This is the init() inside the bar package")
}

func Message() {
	fmt.Println("This is the bar package")
}