Consider the following Go program with multiple init functions across two files in the same package. What will be the output when this program runs?
package main import "fmt" func init() { fmt.Println("Init function 1") } func init() { fmt.Println("Init function 2") } func main() { fmt.Println("Main function") }
Remember that all init functions in a package run before main, and their order is the order they appear in the file.
In Go, multiple init functions in the same package run in the order they appear in the source files before main. So the output shows both init functions first, then main.
Given two packages pkg1 and main, each with an init function, what is the output when the program runs?
package main import ( "fmt" "example.com/pkg1" ) func init() { fmt.Println("Init in main") } func main() { fmt.Println("Main function") } // pkg1 package code: // package pkg1 // import "fmt" // func init() { // fmt.Println("Init in pkg1") // }
Think about package import order and when init functions run.
Go runs init functions in imported packages first, then the importing package's init, then main. So pkg1's init runs before main's init.
Examine the following Go code. Why does it cause a runtime panic when the program starts?
package main import "fmt" var x = initialize() func initialize() int { fmt.Println("Initializing x") panic("panic during initialization") return 42 } func main() { fmt.Println("Main function") }
Think about when package-level variables are initialized.
Package-level variables are initialized before main or init run. Since initialize panics during this phase, the program panics before main starts.
Which option contains a syntax error in the init function declaration?
Remember the init function signature rules in Go.
The init function must have no parameters and no return values. Option A declares a return type string, which is invalid.
Given the following Go program with multiple packages and files, how many times will init functions run in total when the program starts?
Assume:
- Package
mainhas 2 files, each with 1initfunction. - Package
utilshas 1 file with 2initfunctions. - Package
confighas 1 file with 1initfunction. mainimportsutilsandconfig.
Count all init functions in all imported packages and main.
There are 2 init in main, 2 in utils, and 1 in config. Total is 2 + 2 + 1 = 5.