Go Init Functions and Main Function

Init Functions

Init functions are used for package initialization and have the following characteristics:

  1. Init functions are used before program execution to initialize packages, such as initializing variables within a package.
  2. Each source file in a package can contain multiple init functions, which are executed in top-down order.
  3. A package can have multiple init functions.
  4. In the same package, multiple init functions are executed in lexicographical order by filename (from smallest to largest) when they are in different files, then according to the rule for the same file.
  5. The execution order of init functions across different packages is determined by their import dependencies: if there is a dependency, the dependent one is called first; otherwise, the later one is called first.
  6. Init functions cannot be called by other functions but are automatically invoked before the main function executes.

Main Function

The default entry point function of a program (i.e., the main function).

Differences between Init Functions and Main Function

Similarities: Both cannot have any parameters or return values when defined, and both are automatically called by the program.

Differences: Init functions can be used in any package and can be defined multiple times; the main function can only be used in the main package and must be defined only once.

Take a break

πŸ‘‰πŸ‘‰πŸ‘‰ 【BTTH Year EP105】Xiao Yan refined the Ancient Phoenix Blood Essence, then talked with Elder Feng