Challenge - 5 Problems
Channel Closing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of reading from a closed channel?
Consider the following Go code. What will be printed when reading from a closed channel?
Go
package main import "fmt" func main() { ch := make(chan int) go func() { ch <- 42 close(ch) }() val, ok := <-ch fmt.Println(val, ok) val, ok = <-ch fmt.Println(val, ok) }
Attempts:
2 left
💡 Hint
Think about what happens when you read from a closed channel in Go.
✗ Incorrect
When a channel is closed, reading from it returns the zero value and false for the second value. The first read gets the sent value 42 and ok=true. The second read gets zero value 0 and ok=false.
❓ Predict Output
intermediate2:00remaining
What happens when closing a nil channel?
What will happen if you try to close a nil channel in Go?
Go
package main func main() { var ch chan int close(ch) }
Attempts:
2 left
💡 Hint
Think about what nil means for channels and what close expects.
✗ Incorrect
Closing a nil channel causes a runtime panic because nil channels are not initialized and cannot be closed.
❓ Predict Output
advanced2:00remaining
What is the output when closing a channel twice?
What happens when you close a channel twice in Go? Consider this code:
Go
package main import "fmt" func main() { ch := make(chan int) close(ch) close(ch) fmt.Println("Done") }
Attempts:
2 left
💡 Hint
Think about what Go does if you close a channel that is already closed.
✗ Incorrect
Closing a channel twice causes a runtime panic with message 'close of closed channel'.
❓ Predict Output
advanced2:00remaining
What is the output of range over a closed channel?
What will this program print?
Go
package main import "fmt" func main() { ch := make(chan int) go func() { for i := 1; i <= 3; i++ { ch <- i } close(ch) }() for v := range ch { fmt.Print(v, " ") } }
Attempts:
2 left
💡 Hint
Remember how ranging over a channel works when it is closed.
✗ Incorrect
The range loop reads all values sent before the channel is closed, then exits cleanly.
🧠 Conceptual
expert2:00remaining
What is the behavior of sending on a closed channel?
What happens if you try to send a value on a closed channel in Go?
Attempts:
2 left
💡 Hint
Think about what Go does to prevent sending on closed channels.
✗ Incorrect
Sending on a closed channel causes a runtime panic with message 'send on closed channel'.