The main function and the Init function in Go

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Gothere are two reserved functions in it:Initfunction (which can be applied to all Package) andMainfunction (can only be applied toPackage Main). These two functions cannot have any parameters and return values when they are defined. Although a Packageyou can write any number ofInitfunction, but for readability or later maintainability, we strongly recommend that users Packagein each file, write only oneInitfunction.

GoThe program will automatically callInit ()and theMain (), so you don't need to call these two functions anywhere. Each Packagein theInitfunctions are optional, butPackage MainYou must include aMainfunction.

the initialization and execution of the program starts atMainpackage. IfMainpackages are also imported into other packages, they are imported sequentially at compile time. Sometimes a package is imported at the same time by multiple packages, so it will only be imported once (for example, many packages may be usedFMTpackage, but it will only be imported once, because there is no need to import more than once). 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 and then executedInitfunction (if any), and so on. When all the imported packages have been loaded, you will start toMainPackage -level constants and variables in the package are initialized, and then execute theMainin the packageInitfunction (if present), the last executionMainfunction. Explains the entire execution process in detail:

    • go" in the main function and the init function


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.