Home > Backend Development > Golang > When Exactly Does Go's `init()` Function Run?

When Exactly Does Go's `init()` Function Run?

Susan Sarandon
Release: 2024-12-20 22:41:16
Original
240 people have browsed it

When Exactly Does Go's `init()` Function Run?

When Does the init() Function Run?

The init() function is a special function in Go that is called before the main() function of the package. It is commonly used for initializing variables and other setup tasks. But what exactly does the following sentence from Effective Go mean:

"And finally means finally: init is called after all the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been initialized."

This means that the init() function runs after all the global variables in the current package, as well as any imported packages, have been initialized with their default values. It's important to note that the order of initialization is based on the lexical order of the package files, rather than the order in which the imports are declared.

As an example:

var GlobalVar1 = 10

func init() {
    GlobalVar1 = 20
}

func main() {
    // GlobalVar1 is 20
}
Copy after login

In this example, the init() function is called after GlobalVar1 has been initialized to 10, and it overrides the value of GlobalVar1 to 20 before the main() function is called.

It's worth mentioning that the init() function is always called, regardless of whether or not the package has a main() function. This means that if you import a package that has an init() function, it will be executed before the init() function of your own package.

Additionally, multiple init() functions can be defined within a single package, and they will be executed in the order they appear in the source file. This allows you to perform multiple initialization tasks in a specific order.

The above is the detailed content of When Exactly Does Go's `init()` Function Run?. 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