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:
- Automatic call:
init
The function is automatically called when the program is running, without manual call. When the package is imported,init
the function is executed automatically and only once. - Not callable manually: Since
init
the function is automatically executed as part of the initialization of the package, we cannot call it explicitly in the code . - Import package trigger:
init
the execution of the function is when the package is imported - 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. - No parameters and return value:
init
Functions have no parameters and return value, because they are automatically called by the Go language runtime system. - Concurrency safety:
init
Functions are safe in a concurrent environment, and multipleinit
functions can be executed concurrently. However, it is recommendedinit
to avoid introducing race conditions inside functions.
func init() {
fmt.Println("initial...")
}