Challenge - 5 Problems
Goroutine Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Goroutine execution order
What is the output of this Go program?
Go
package main import ( "fmt" "time" ) func main() { go fmt.Println("Hello from goroutine") fmt.Println("Hello from main") time.Sleep(100 * time.Millisecond) }
Attempts:
2 left
💡 Hint
Remember that goroutines run concurrently and main may finish before they print unless you wait.
✗ Incorrect
The main function prints first, then the goroutine prints after. The Sleep allows the goroutine to run before the program exits.
❓ Predict Output
intermediate2:00remaining
Goroutine variable capture
What will be printed by this Go program?
Go
package main import ( "fmt" "time" ) func main() { for i := 0; i < 3; i++ { go func(i int) { fmt.Println(i) }(i) } time.Sleep(100 * time.Millisecond) }
Attempts:
2 left
💡 Hint
Think about how the loop variable is captured by the goroutine's closure.
✗ Incorrect
Passing the loop variable as a parameter to the goroutine captures its value at each iteration, so the goroutines print 0, 1, and 2 respectively.
🔧 Debug
advanced2:00remaining
Detecting goroutine leak
What problem does this Go code cause?
Go
package main import ( "fmt" "time" ) func worker(ch chan int) { for { val, ok := <-ch if !ok { return } fmt.Println(val) } } func main() { ch := make(chan int) go worker(ch) ch <- 1 ch <- 2 // Missing close(ch) select {} }
Attempts:
2 left
💡 Hint
Think about what happens when the worker goroutine waits on a channel that never closes.
✗ Incorrect
The worker goroutine waits forever on the channel because it is never closed, causing a goroutine leak.
❓ Predict Output
advanced2:00remaining
Goroutine synchronization with WaitGroup
What is the output of this Go program?
Go
package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() fmt.Println("First goroutine") }() go func() { defer wg.Done() fmt.Println("Second goroutine") }() wg.Wait() fmt.Println("All done") }
Attempts:
2 left
💡 Hint
WaitGroup waits for all goroutines to finish before continuing.
✗ Incorrect
The program waits for both goroutines to finish printing before printing "All done".
🧠 Conceptual
expert2:00remaining
Goroutine lifecycle states
Which of the following correctly describes the lifecycle states of a goroutine?
Attempts:
2 left
💡 Hint
Think about the main states a goroutine goes through from creation to termination.
✗ Incorrect
Goroutines are created, run, may wait (blocked), and then die (dead) when finished.