Challenge - 5 Problems
Go Program Stability Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of deferred function with panic
What is the output of this Go program?
Go
package main import "fmt" func main() { defer fmt.Println("deferred") panic("panic occurred") fmt.Println("after panic") }
Attempts:
2 left
💡 Hint
Remember that deferred functions run before the program exits due to panic.
✗ Incorrect
In Go, deferred functions run even if a panic occurs. So "deferred" prints before the panic message.
❓ Predict Output
intermediate2:00remaining
Recover usage in goroutine
What will this Go program print?
Go
package main import ( "fmt" "time" ) func safeGo() { defer func() { if r := recover(); r != nil { fmt.Println("Recovered from panic") } }() panic("panic in goroutine") } func main() { go safeGo() time.Sleep(100 * time.Millisecond) fmt.Println("main finished") }
Attempts:
2 left
💡 Hint
Recover only works if called inside deferred function in the same goroutine.
✗ Incorrect
The panic inside safeGo is recovered, so "Recovered from panic" prints. Then main prints "main finished".
❓ Predict Output
advanced2:00remaining
Race condition detection output
What will happen when running this Go program with the race detector enabled?
Go
package main import ( "fmt" "sync" ) func main() { var x int var wg sync.WaitGroup wg.Add(2) go func() { x = 1 wg.Done() }() go func() { x = 2 wg.Done() }() wg.Wait() fmt.Println(x) }
Attempts:
2 left
💡 Hint
Two goroutines write to the same variable without synchronization.
✗ Incorrect
The variable x is written concurrently without locks, causing a data race detected by the race detector.
❓ Predict Output
advanced2:00remaining
Effect of closing a channel twice
What happens when this Go program runs?
Go
package main func main() { ch := make(chan int) close(ch) close(ch) }
Attempts:
2 left
💡 Hint
Closing a channel twice is not allowed in Go.
✗ Incorrect
Closing a channel that is already closed causes a runtime panic.
❓ Predict Output
expert2:00remaining
Output of select with nil channel
What is the output of this Go program?
Go
package main import "fmt" func main() { var ch chan int // nil channel select { case ch <- 1: fmt.Println("sent 1") case <-ch: fmt.Println("received") default: fmt.Println("default case") } }
Attempts:
2 left
💡 Hint
Operations on nil channels block forever unless default case is present.
✗ Incorrect
Both send and receive on nil channel block, so select chooses default immediately.