Go language init and main functions

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

There are two reserved functions in go: the INIT function and the main function. Here's a look at the similarities and differences between the two functions.
The same point: two functions cannot have any parameters and return values when defined, and the Go program automatically calls.
Different points: Init can be applied to any package, and multiple definitions can be repeated. The main function can only be used in the main package, and only one can be defined.

Let's talk about the order of execution of the two functions:
The init () call order for the same go file is from top to bottom
For different files in the same package, the Init () function in each file is called from small to large in order of file name strings, for
For different packages, if they do not depend on each other, the Init () in the package is called in the order of "import first call" in the main package
If the package has dependencies, first call Init () in the first dependent package
Finally call the main function

Astaxie" Go Web programming

PS: If println or print is used in the INIT function You will find that these two do not execute in the same order as you would think. These two functions are only recommended for use in test environments, not for formal environments.

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.