Junior — Middle
Can you explain the purpose of the init() function in the context of programming?
sobes.tech AI
Answer from AI
In the Go language, the init() function is used to initialize a package before the main program executes. It is automatically called once when the package is loaded, prior to the call of the main() function.
Purpose of init():
- Initialization of variables, constants, or structures that require complex logic.
- Setting up the package state, such as registering handlers or connecting to resources.
Example:
package main
import "fmt"
var config string
func init() {
config = "initialized"
fmt.Println("init called")
}
func main() {
fmt.Println("main called")
fmt.Println("config:", config)
}
The output will be:
init called
main called
config: initialized
Thus, init() helps prepare the environment before the main program logic runs.