The main identifier is ubiquitous, and every Go program starts with a main function in a package called Main, and when the main function returns, the execution of the program ends. The Init function also plays a special role, and next we will describe the properties of the Init function and describe how to use them. The INIT function is defined at the package level and is used primarily for:-initializing variables that cannot be initialized by an initialization expression-checking or fixing the state of the program-registering-performing only one calculation at a time-more other occasions besides some of the differences that will be discussed below, you can also place any [valid] in the regular function ( Https://golang.org/ref/spec#FunctionBody) content. # # The initialization of the package to use the imported package first needs to initialize it, which is done by Golang's running system, mainly including (order is important): 1. Initialize the imported package (recursive definition) 2. Calculates and assigns an initial value of 3 at the package level for the declared variable. Execute the INIT function within the package (the following blank identifier is an example) > will only be initialized once, no matter how many times the package is imported. # # # There are many files in the package go, if the variables and functions are in multiple files of the package, then what is the initialization of the variables and the order in which the Init functions are called? First, the initialization dependency mechanism will start (more [initialization dependencies in Go] (https://studygolang.com/articles/13158)) when the initial dependency mechanism is complete, you need to decide ' a.go ' and ' z.go ' The initialization variables in the will be processed earlier, depending on the order of the files presented to the compiler. If the ' Z.go ' is first passed to the build system, then the initialization of the variable will be more than the first step in ' A.go ', which also applies to the Init function's triggering. The Go Language specification recommends that we always pass in the same order, that is, the file name in the package is passed in lexical order:> to ensure repeatable initialization behavior, the build system encourages multiple files belonging to the same package to be presented to the compiler in the order of the lexical file names. But relying on a particular order is a way of doing programs that do not care about portability (but it is not recommended to rely on INIT initialization order). Let's look at an example to see how they work together: # # # Sandbox.go "Gopackage mainimport" Fmt "var _ int64 = S () func init () {FMT. Println ("Init in Sandbox.go")}func s () Int64 {FMT. Println ("calling S () in Sandbox.go") return 1}func main () {FMT. Println ("main")} ' # # # a.go ' gopackage mainimport "Fmt" var _ int64 = A () func init () {FMT. Println ("Init in A.go")}func A () int64 {FMT. Println ("Calling A () in A.go") Return 2} "# # Z.go" "Gopackage mainimport" Fmt "var _ int64 = Z () func init () {FMT. Println ("Init in Z.go")}func Z () Int64 {FMT. Println ("Calling Z () in Z.go") return 3} "# # # Program output: ' ' calling A () in a.gocalling s () in Sandbox.gocalling Z () in Z.goinit In A.goinit in Sandbox.goinit in Z.gomain "# # Property The init function does not require arguments and returns no values, similar to main, where the identifier init is not declared so it cannot be referenced:" ' Gopackage mai Nimport "FMT" func init () {FMT. Println ("Init")}func Main () {init ()} "will give a" Undefined:init "error at compile time. (The init function cannot be referenced) > formally, the init designator does not introduce bindings, just as the blank identifier ('_') behaves. Many init functions can be defined in the same package or file: # # # sandbox.go ' gopackage mainimport "FMT" func init () {FMT. Println ("Init 1")}func init () {FMT. Println ("Init 2")}func Main () {FMT. Println ("main")} ' # # # utils.go ' gopackage mainimport "FMT" func init () {FMT. PRintln ("Init 3")} ' # # # output: ' init 1init 2init 3main ' init function is also used frequently in the standard library, for example: [*main*] (https://github.com/golang/go/ BLOB/2878CF14F3BB4C097771E50A481FEC43962D7401/SRC/MATH/POW10.GO#L33), [*bzip2*] (https://github.com/golang/go/ blob/2878cf14f3bb4c097771e50a481fec43962d7401/src/compress/bzip2/bzip2.go#l479) and [*image*] (https://github.com/ golang/go/blob/2d573eee8ae532a3720ef4efbff9c8f42b6e8217/src/image/gif/reader.go#l511) package. The most common use of the INIT function is to assign a value to the part of the initialization expression that cannot be computed: ' ' govar precomputed = [20]float64{}func init () {var current float64 = 1 Precomp Uted[0] = Current for I: = 1; I < Len (precomputed); i++ {Precomputed[i] = precomputed[i-1] * 1.2}} "use for loop as [* expression *] (https://golang.org/ref/spec#Expression) (Go Language) is not possible, so putting these into the INIT function can be a good solution to these problems. # # # Just to use the package's side effects (initialization of the package), importing the package go language is very strict with unused imports. Sometimes a programmer importing a package may only want to use the functions of the INIT function, such as some boot work. A blank identifier is a good way: "Goimport _" Image/png "" it even in [*image*] (https://github.com/golang/go/blob/ 0104A31B8FBCBE52728A08867B26415D282C35D2/SRC/IMAGE/IMAGE.GO#L10) is mentioned in the package.If the above is helpful to you please follow me to write the story of the future, which will also be my motivation. ---# # Reference-[The Go programming Language specification-the go programming Language] (https://golang.org/ref/spec#Package _initialization)-[Blocks in Go] (https://studygolang.com/articles/12632)-[initialization dependencies in Go] (https:/ /studygolang.com/articles/13158)
via:https://medium.com/golangspec/init-functions-in-go-eac191b3860a
Author: Michałłowicki Translator: Flexiwind proofreading: polaris1119
This article by GCTT original compilation, go language Chinese network honor launches
This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove
275 Reads