Golang / GoLang Concurrency Mastery Interview Questions
What happens when you send to, receive from, or close a nil or closed channel?
This table is essential interview knowledge. Mistakes here produce panics and deadlocks that are notoriously difficult to debug.
| Operation | Nil channel | Open, empty channel | Open, has data | Closed channel |
|---|---|---|---|---|
| Send (ch <- v) | Blocks forever | Blocks | Sends OK | PANIC |
| Receive (<-ch) | Blocks forever | Blocks | Returns value, ok=true | Returns zero value, ok=false |
| Close (close(ch)) | PANIC | Closes successfully | Closes; remaining data still readable | PANIC |
// Nil channel: always blocks (send or receive) var ch chan int // ch <- 1 // deadlock // <-ch // deadlock // close(ch) // PANIC: close of nil channel // Closed channel: reads drain buffered data then return zero done := make(chan struct{}) close(done) v, ok := <-done fmt.Println(v, ok) // {} false // done <- struct{}{} // PANIC: send on closed channel // Comma-ok idiom: detect channel closure ch2 := make(chan int, 2) ch2 <- 1; ch2 <- 2 close(ch2) for { v, ok := <-ch2 if !ok { break } // channel closed and drained fmt.Println(v) } // Idiomatic: range handles closure automatically ch3 := make(chan int) go func() { ch3 <- 1; ch3 <- 2; close(ch3) }() for v := range ch3 { fmt.Println(v) } // exits on close // GOLDEN RULE: only the SENDER should close a channel // A receiver cannot know when the sender is done
More Related questions...