Golang / GoLang Concurrency Mastery Interview Questions
How do you use a nil channel in select to dynamically enable or disable cases?
A nil channel case in select is permanently disabled — it never fires. This allows you to dynamically enable or disable select cases at runtime by toggling a channel variable between nil and a real channel, without any if-else branching inside the select.
// Scenario: drain primary channel; only then activate secondary
func processOrdered(primary, secondary <-chan string) {
activePrimary := primary
activeSecondary := (<-chan string)(nil) // disabled initially
for activePrimary != nil || activeSecondary != nil {
select {
case v, ok := <-activePrimary:
if !ok {
activePrimary = nil // disable primary case
activeSecondary = secondary // enable secondary case
} else {
fmt.Println("primary:", v)
}
case v, ok := <-activeSecondary:
if !ok {
activeSecondary = nil
} else {
fmt.Println("secondary:", v)
}
}
}
}
// Another use: conditional send — nil channel means 'skip this send'
func maybeSend(notify chan<- string, msg string, doSend bool) {
var ch chan<- string
if doSend { ch = notify } // ch is nil if !doSend
select {
case ch <- msg: // disabled when ch is nil — never fires
default:
}
}
// Key property:
// A nil channel in select is excluded from consideration entirely.
// It does not block; it does not fire. It simply doesn't exist.
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...
