Challenge - 5 Problems
Goroutine Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of simple goroutine execution
What is the output of this Go program?
Go
package main import ( "fmt" "time" ) func main() { go fmt.Println("Hello from goroutine") time.Sleep(100 * time.Millisecond) fmt.Println("Main function finished") }
Attempts:
2 left
💡 Hint
Think about how goroutines run concurrently and why we use Sleep here.
✗ Incorrect
The goroutine prints first, but since goroutines run concurrently, the main function waits 100ms to let it finish before printing its own message.
❓ Predict Output
intermediate2:00remaining
Goroutine variable capture behavior
What will be printed by this Go program?
Go
package main import ( "fmt" "time" ) func main() { for i := 0; i < 3; i++ { go func() { fmt.Println(i) }() } time.Sleep(100 * time.Millisecond) }
Attempts:
2 left
💡 Hint
Consider how the loop variable is captured by the goroutine function.
✗ Incorrect
The anonymous function captures the variable i by reference, so when the goroutines run, i has already reached 3.
🔧 Debug
advanced2:00remaining
Identify the error in goroutine creation
What error will this Go program produce when run?
Go
package main func main() { go func() { println("Running") }() }
Attempts:
2 left
💡 Hint
Think about what happens to the main function after starting a goroutine.
✗ Incorrect
The main function exits immediately after starting the goroutine, so the goroutine may not run before program exit.
❓ Predict Output
advanced2:00remaining
Goroutine with argument capture
What is the output of this Go program?
Go
package main import ( "fmt" "time" ) func main() { for i := 0; i < 3; i++ { go func(n int) { fmt.Println(n) }(i) } time.Sleep(100 * time.Millisecond) }
Attempts:
2 left
💡 Hint
Look at how the loop variable is passed as an argument to the goroutine function.
✗ Incorrect
Passing i as an argument copies its value at each iteration, so each goroutine prints its own value.
🧠 Conceptual
expert2:00remaining
Goroutine scheduling and output order
Given this Go program, which output is guaranteed?
Go
package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() fmt.Println("First") }() go func() { defer wg.Done() fmt.Println("Second") }() wg.Wait() }
Attempts:
2 left
💡 Hint
Consider how goroutines are scheduled and the use of WaitGroup.
✗ Incorrect
The WaitGroup ensures both goroutines finish before main exits, but their print order is not guaranteed.