The Init function and main function in 006_golang

Source: Internet
Author: User

One

(1) Init function

The init function is available in the package main, which can appear multiple times in the same package in the other package.

(2) Main function

The main function can only be in package main.

(3) execution order such as:

There are two reserved functions in Golang: the init function (which can be applied to all package) and the main function (can only be applied to package main). These two functions cannot have any parameters and return values when they are defined. Although it is possible to write any number of INIT functions in a package, it is strongly recommended that users write only one init function per file in a single document, whether for readability or later maintainability. The GO program automatically calls 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 with the main package. If the main package also imports other packages, they are imported sequentially at compile time. Sometimes a package is imported at the same time by multiple packages,
Then 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 are imported, and then the package-level constants and variables in those packages are initialized, followed by the Init function (if any), and so on.
When all the imported packages are loaded, the package-level constants and variables in the main package are initialized, and the INIT function in the main package (if present) is executed, and the main function is finally executed. Explains the entire execution process in detail:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.