Home  >  Article  >  Backend Development  >  How does golang main return value

How does golang main return value

(*-*)浩
(*-*)浩Original
2019-12-17 09:29:513725browse

How does golang main return value

The init function can be in package main, in other packages, and can appear multiple times in the same package.

main function                                                                                                                           (recommended learning: go)

The main function can only be in package main.

Execution order

There are two reserved functions in golang: init function (can be applied to all packages) and main function (can only be applied to package main). These two functions cannot have any parameters or return values ​​when they are defined.

Although you can write any number of init functions in a package, for both readability and future maintainability, we strongly recommend that users write each file in a package Just write an init function.

The go program will 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 package main must contain a main function.

The initialization and execution of the program start from the main package.

If the main package also imports other packages, they will be imported in sequence during compilation. 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 it multiple times).

When a package is imported, if the package also imports other packages, the other packages will be imported first, and then the package-level constants and variables in these packages will be initialized, and then init will be executed. function (if any), 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 will be executed (if it exists), and finally main will be executed. function. The following figure explains the entire execution process in detail:

How does golang main return value

The above is the detailed content of How does golang main return value. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn