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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
