main function and init function in Go

 There are two reserved functions in Go: init (applies to all packages) and main (applies only to package main). These two functions cannot have any parameters and return values ​​when they are defined. Although any number of init functions can be written in a package , both for readability and future maintainability, we strongly recommend that users only write one init function per file in a package.

       Go programs automatically call init() and main(), so you don't need to call these two functions anywhere. The init function in each package is optional, but the package main must contain a main function.

    The initialization and execution of the program starts from the main package. If the main package also imports other packages, they will be imported in turn at compile time. Sometimes a package will be imported by multiple packages at the same time, so it will only be imported once (for example, many packages may use the fmt package, but it will only be imported once, because there is no need to import multiple times). When a package is imported, if the package also imports other packages, the other packages will be imported first, then the package-level constants and variables in these packages will be initialized, and then the init function (if any) will be executed. ),And so on. When all imported packages are loaded , the package-level constants and variables in the main package will be initialized, then the init function in the main package (if it exists) will be executed, and finally the main function will be executed. The following diagram explains the entire execution process in detail:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324828945&siteId=291194637