Challenge - 5 Problems
Go Package Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of accessing package-level variables
What is the output of this Go program?
Go
package main import "fmt" var packageVar = 10 func main() { fmt.Println(packageVar) }
Attempts:
2 left
💡 Hint
Package-level variables are accessible inside functions within the same package.
✗ Incorrect
The variable packageVar is declared at package level and initialized to 10. It is accessible inside main(), so printing it outputs 10.
❓ Predict Output
intermediate2:00remaining
Accessing unexported variable from another package
Given two packages, main and utils, where utils has an unexported variable, what happens when main tries to access it?
Go
package utils var secret = 42 package main import ( "fmt" "utils" ) func main() { fmt.Println(utils.secret) }
Attempts:
2 left
💡 Hint
In Go, identifiers starting with lowercase letters are unexported and not accessible outside their package.
✗ Incorrect
The variable secret starts with a lowercase letter, so it is unexported and cannot be accessed from main package. This causes a compilation error.
🔧 Debug
advanced2:00remaining
Why does this code fail to compile?
Consider this Go code snippet. Why does it fail to compile?
Go
package main import "fmt" func main() { fmt.Println(helperVar) } var helperVar = 5
Attempts:
2 left
💡 Hint
Package-level variables are initialized before main runs, regardless of their position in the file.
✗ Incorrect
In Go, package-level variables are initialized before main() runs, so helperVar is accessible even if declared after main(). The code compiles and prints 5.
❓ Predict Output
advanced2:00remaining
Shadowing package-level variable inside function
What is the output of this Go program?
Go
package main import "fmt" var count = 100 func main() { count := 50 fmt.Println(count) }
Attempts:
2 left
💡 Hint
A variable declared inside a function with := shadows the package-level variable.
✗ Incorrect
Inside main(), count := 50 declares a new local variable count that shadows the package-level count. So printing count outputs 50.
❓ Predict Output
expert3:00remaining
Package variable initialization order with init functions
What is the output of this Go program?
Go
package main import "fmt" var x = initializeX() func initializeX() int { fmt.Println("initializeX called") return 42 } func init() { fmt.Println("init function called") } func main() { fmt.Println("main function called") fmt.Println(x) }
Attempts:
2 left
💡 Hint
Package variables are initialized before init functions run.
✗ Incorrect
First, package-level variables are initialized, so initializeX() runs and prints its message. Then init() runs. Finally main() runs. So the output order is initializeX called, init function called, main function called, 42.