0
0
Goprogramming~5 mins

Channel closing behavior in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What happens when you close a channel in Go?
Closing a channel means no more values can be sent on it. Receivers can still receive remaining values until the channel is empty, then they get the zero value.
Click to reveal answer
beginner
Can you send values on a closed channel?
No. Sending on a closed channel causes a runtime panic (error).
Click to reveal answer
intermediate
What does a receive operation return when the channel is closed and empty?
It returns the zero value of the channel's type and false for the second value if using the two-value receive form.
Click to reveal answer
intermediate
How can you check if a channel is closed when receiving?
Use the two-value receive: v, ok := <-ch. If ok is false, the channel is closed and empty.
Click to reveal answer
intermediate
Is it safe to close a channel from multiple goroutines?
No. Closing a channel multiple times causes a panic. Only one goroutine should close the channel.
Click to reveal answer
What happens if you try to send a value on a closed channel?
AThe program panics (runtime error).
BThe value is silently ignored.
CThe value is buffered until the channel reopens.
DThe send blocks forever.
When receiving from a closed channel, what value do you get?
AThe receive blocks forever.
BThe last sent value again.
CAn error is returned.
DThe zero value of the channel's type.
How do you detect if a channel is closed when receiving?
AUse a select statement with default case.
BUse the two-value receive: v, ok := <-ch.
CCheck if the channel is nil.
DYou cannot detect if a channel is closed.
Who should close a channel?
AAny goroutine at any time.
BThe receiver, when done receiving.
CThe sender, when no more values will be sent.
DChannels do not need to be closed.
What happens if multiple goroutines close the same channel?
AThe program panics at the second close.
BThe channel closes safely once.
CThe channel reopens automatically.
DThe closes are ignored after the first.
Explain what happens when a Go channel is closed and how receivers behave afterwards.
Think about what sending and receiving do after closing.
You got /4 concepts.
    Describe best practices for closing channels in concurrent Go programs.
    Who should close and why?
    You got /4 concepts.