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 formain
Package, and eachmain
Package can only beA main ()
function- But for the
init()
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 runs
For package initialization (custom variables, instantiation of communication connections)Each package
,Each program file
You can have multiple init() at the same time, butDon't recommend
- Multiple files in the same package
Init () execution order
Golang is not clear - Different package
init()
Execution sequence, according toImport package dependencies
decision init()
Cannot be called by other functions while automaticallyBefore main is executed
Is 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 follows
Resolve the dependencies
In order of execution,Packages without dependencies are initialized first. - The first initialization is within the scope of each package
constant
,variable
(where constant precedes variable), and then executes inside the packageinit()
. - Same package, file can
At the same time
Multiple init (). - Init () is like main(),
There are no arguments or return values
Cannot be called by other functions. - Same package, same file
Multiple init ()
The order of execution is not clear.
Import — > const — > var — > init() — > main()