Home > Backend Development > Golang > When and How Does Go's `init()` Function Execute?

When and How Does Go's `init()` Function Execute?

Linda Hamilton
Release: 2024-12-24 10:26:16
Original
437 people have browsed it

When and How Does Go's `init()` Function Execute?

When Does the init() Function Run?

The init() function is a special function in Go that runs during package initialization. It is typically used to perform initialization tasks that cannot be handled by the package's main() function.

According to the Go documentation, the init() function is called after all the variable declarations in the package have evaluated their initializers. This means that all global variables and their initializers will have been processed before the init() function is executed.

The following example demonstrates this behavior:

var WhatIsThe = AnswerToLife()

func AnswerToLife() int { // 1
    return 42
}

func init() { // 2
    WhatIsThe = 0
}

func main() { // 3
    if WhatIsThe == 0 {
        fmt.Println("It's all a lie.")
    }
}
Copy after login

In this example, the AnswerToLife() function (1) is guaranteed to run before the init() function (2) is called. The init() function is then guaranteed to run before the main() function (3) is called.

Note that the init() function is always called, regardless of whether or not there is a main() function. Therefore, if you import a package that has an init() function, it will be executed.

The above is the detailed content of When and How Does Go's `init()` Function Execute?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template