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.
More Related questions...