Introduction
Module initialization helps set up things before your program starts running main code. It prepares data or settings automatically.
func init() {
// code to run before main
}package main import "fmt" func init() { fmt.Println("Setup before main") } func main() { fmt.Println("Main function runs") }
package main import "fmt" func init() { fmt.Println("First init") } func init() { fmt.Println("Second init") } func main() { fmt.Println("Main runs") }
package main import "fmt" func init() { fmt.Println("Initializing module") } func main() { fmt.Println("Program started") }
init function in a Go module?init in Goinit function is designed to run automatically before the main function starts.main, init is used for setup tasks, not for program entry or input handling.main starts -> Option Ainit runs before main [OK]init runs before main automatically [OK]init with maininit handles user inputinit must be called manuallyinit function in Go?func, followed by the function name and parentheses.init function naming rulesinit function must be lowercase and have no parameters or return values.init syntax = func init() {} [OK]init with empty parentheses [OK]Init instead of initfunctioninitpackage main
import "fmt"
func init() {
fmt.Println("Init 1")
}
func init() {
fmt.Println("Init 2")
}
func main() {
fmt.Println("Main")
}init functions execution orderinit functions run automatically before main, in the order they appear in the source file.main function.init run in order before main [OK]init run top to bottom before main [OK]main runs before initinit functions run in random orderinit functionsinit function:package main
func init() {
fmt.Println("Starting")
}
func main() {
fmt.Println("Running")
}fmt.Println but does not import the fmt package, causing a compile error.init can print output, multiple init are optional, and main must be lowercase.import "fmt" to fix [OK]fmtinit cannot printmain functioninit to do this?var config map[string]string
func init() {
// What should go here?
}initconfig variable must be assigned a new map using make before adding keys.config inside init, not affecting the global. config = nil sets config to nil, which is not useful.make to initialize maps before use [OK]make to initialize maps before adding keys [OK]init creates local variablePass the test and this pattern moves unknown