0
0
Goprogramming~20 mins

Package scope rules in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Package Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
}
ACompilation error: packageVar undefined
B0
C10
DRuntime panic
Attempts:
2 left
💡 Hint
Package-level variables are accessible inside functions within the same package.
Predict Output
intermediate
2: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)
}
A0
B42
CRuntime panic
DCompilation error: secret is not exported by package utils
Attempts:
2 left
💡 Hint
In Go, identifiers starting with lowercase letters are unexported and not accessible outside their package.
🔧 Debug
advanced
2: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
ACompilation error: undefined helperVar
BIt compiles and prints 5
CCompilation error: helperVar used before declaration
DRuntime panic: nil pointer dereference
Attempts:
2 left
💡 Hint
Package-level variables are initialized before main runs, regardless of their position in the file.
Predict Output
advanced
2: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)
}
A50
B100
CCompilation error: count redeclared
D0
Attempts:
2 left
💡 Hint
A variable declared inside a function with := shadows the package-level variable.
Predict Output
expert
3: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)
}
A
initializeX called
init function called
main function called
42
B
init function called
initializeX called
main function called
42
C
main function called
initializeX called
init function called
42
DCompilation error
Attempts:
2 left
💡 Hint
Package variables are initialized before init functions run.