0
0
Goprogramming~20 mins

Program stability concepts in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Program Stability Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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")
}
Adeferred
B
deferred
panic: panic occurred
C
after panic
deferred
D
panic: panic occurred
deferred
Attempts:
2 left
💡 Hint
Remember that deferred functions run before the program exits due to panic.
Predict Output
intermediate
2: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")
}
A
main finished
Recovered from panic
B
Recovered from panic
main finished
C
panic: panic in goroutine
main finished
Dpanic: panic in goroutine
Attempts:
2 left
💡 Hint
Recover only works if called inside deferred function in the same goroutine.
Predict Output
advanced
2: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)
}
APrints 1 or 2, race detector reports data race
BAlways prints 1, no race detected
CCompilation error due to missing synchronization
DAlways prints 2, no race detected
Attempts:
2 left
💡 Hint
Two goroutines write to the same variable without synchronization.
Predict Output
advanced
2: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)
}
ACompilation error
BDeadlock error
CPanic: close of closed channel
DProgram exits normally
Attempts:
2 left
💡 Hint
Closing a channel twice is not allowed in Go.
Predict Output
expert
2: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")
    }
}
Adefault case
Bsent 1
Creceived
DDeadlock
Attempts:
2 left
💡 Hint
Operations on nil channels block forever unless default case is present.