Give the complete table of channel operation behavior for nil, open, and closed channels.
Question 185MediumGo 1.22 to 1.25
| Operation | nil channel | open channel | closed channel |
|---|---|---|---|
send ch <- v | blocks forever | blocks until received/buffer space | panic |
receive <-ch | blocks forever | blocks until value | drains buffer, then zero value, ok=false |
close(ch) | panic | succeeds | panic |
len/cap | 0 | queued / capacity | remaining queued / capacity |
What the interviewer is looking for: you should know all three panics (send on closed, close of nil, double close) and understand that "blocks forever" on nil is a feature that select uses to turn cases off dynamically. Candidates often say that receiving from a closed channel panics. It does not. It returns buffered values first and then zero values forever.
More on Channels & select
- Q183What is the difference between buffered and unbuffered channels in terms of synchronization semantics?
- Q184Describe the runtime internals of a channel (
hchan). - Q186What does this print? (receiving from a closed buffered channel)
- Q187Explain the comma-ok idiom on channel receive. When is it needed and when is
for rangebetter? - Q188Who should close a channel, and why? What are the rules?
- Q189How do you safely close a channel that might be closed by multiple goroutines?