Welcome To Golang By Example

Order of execution of a Go program

Table of Contents

Overview

Below the order of execution of a go program.

Note here that package initialization is only done once even if it is imported several times.

For example, if main package imports package a and in turn package a imports package b, then below will be the order

Example

Let’s see a program for the same.

go.mod

module sample

go 1.14

sample/b/b1.go

package b

import (
	"fmt"
)

func init() {
	fmt.Println("Init: b1")
}

func TestB() error {
	return nil
}

sample/b/b2.go

package b

import (
	"fmt"
)

func init() {
	fmt.Println("Init: b2")
}

sample/a/a1.go

package a

import (
	"fmt"
	"sample/b"
)

func init() {
	fmt.Println("Init: a1")
}

func TestA() error {
	return b.TestB()
}

sample/a/a2.go

package a

import (
	"fmt"
)

func init() {
	fmt.Println("Init: a2")
}

sample/main.go

package main

import (
	"fmt"
	"sample/a"
)

func init() {
	fmt.Println("Init: main")
}
func main() {
	fmt.Println("Main Function Executing")
	a.TestA()
}

Output

Init: b1
Init: b2
Init: a1
Init: a1
Init: main
Main Function Executing

Notice in above example that init function in source files of package b are run first. Then init function in source files of package a is run and then init function in source file of main package is run. After that main function is run