Introduction to init function in Go language

init()The main purpose of the function is to perform initialization operations when the package is imported, such as setting global variables, performing configuration initialization, establishing database connections, etc.

In the Go language, init()functions have characteristics, as follows:

  1. Automatic call: initThe function is automatically called when the program is running, without manual call. When the package is imported, initthe function is executed automatically and only once.
  2. Not callable manually: Since initthe function is automatically executed as part of the initialization of the package, we cannot call it explicitly in the code .
  3. Import package trigger: initthe execution of the function is when the package is imported
  4. In-package sequential execution: For multiple functions in the same package init, they are called in the order in which they appear in the source file. This means that the order of initialization operations at the package level can be controlled.
  5. No parameters and return value: initFunctions have no parameters and return value, because they are automatically called by the Go language runtime system.
  6. Concurrency safety: initFunctions are safe in a concurrent environment, and multiple initfunctions can be executed concurrently. However, it is recommended initto avoid introducing race conditions inside functions.
func init() {
    
    
	fmt.Println("initial...")
}

Guess you like

Origin blog.csdn.net/qq_35760825/article/details/131758621