This is the third day of my participation in the gengwen Challenge, the details of the activity view: Gengwen Challenge if ❤️ my article is helpful, welcome to like, follow. This is the biggest encouragement for me to continue my technical creation. More previous posts on my personal blog

Golang init () function

Let me give you an example

package main

import "fmt"

func init(a)  {
	fmt.Println("init() 1:", a)
}

func init(a)  {
	fmt.Println("init() 2:", a)
}

var a = 10
const b = 100

func main(a) {
	fmt.Println("main() :", a)
}

// Execution result
// init() 1: 10
// init() 2: 10
// main() : 10
Copy the code

What is the init ()

The default two functions, main() and init(), were retained during the Go language design.

The difference between the two is:

  • main()Function can only be used formainPackage, and eachmainPackage can only beA main ()function
  • But for theinit()Function, can be used in all packages. And you can write as many as you want in a program (or even a file)init()Function.

Note: You can write any number of init() functions in a program (or even a file) without any benefit in maintaining code readability or troubleshooting

The init () characteristics

  • init()Used forBefore program runsFor package initialization (custom variables, instantiation of communication connections)
  • Each package,Each program fileYou can have multiple init() at the same time, butDon't recommend
  • Multiple files in the same packageInit () execution orderGolang is not clear
  • Different packageinit()Execution sequence, according toImport package dependenciesdecision
  • init()Cannot be called by other functions while automaticallyBefore main is executedIs called

— Effective_go

When is init() executed

The init() function is part of the Golang program initialization package.

In Golang, the program initialization precedes main() : The Runtime initializes each imported package.

  • The initialization sequence is as followsResolve the dependenciesIn order of execution,Packages without dependencies are initialized first.
  • The first initialization is within the scope of each packageconstant,variable(where constant precedes variable), and then executes inside the packageinit().
  • Same package, file canAt the same timeMultiple init ().
  • Init () is like main(),There are no arguments or return valuesCannot be called by other functions.
  • Same package, same fileMultiple init ()The order of execution is not clear.

Import — > const — > var — > init() — > main()