0
0
Goprogramming~20 mins

Channel closing behavior in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Channel Closing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
}
A
42 true
0 false
B
42 true
42 true
C
0 false
0 false
D
42 false
0 false
Attempts:
2 left
💡 Hint
Think about what happens when you read from a closed channel in Go.
Predict Output
intermediate
2: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)
}
ADeadlock at runtime
BProgram exits normally
CCompilation error: cannot close nil channel
DPanic: close of nil channel
Attempts:
2 left
💡 Hint
Think about what nil means for channels and what close expects.
Predict Output
advanced
2: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")
}
APanic: close of closed channel
BPrints "Done" and exits normally
CCompilation error: cannot close channel twice
DDeadlock at runtime
Attempts:
2 left
💡 Hint
Think about what Go does if you close a channel that is already closed.
Predict Output
advanced
2: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, " ")
    }
}
A1 2 3 0
B1 2 3
C1 2
DDeadlock at runtime
Attempts:
2 left
💡 Hint
Remember how ranging over a channel works when it is closed.
🧠 Conceptual
expert
2: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?
AThe send succeeds and the value is lost
BThe send blocks forever causing a deadlock
CThe program panics at runtime with 'send on closed channel'
DThe value is silently discarded
Attempts:
2 left
💡 Hint
Think about what Go does to prevent sending on closed channels.