Multiplex Dynamic Channels With reflect.Select
Combine a runtime slice of channels into []reflect.SelectCase using reflect.Select, handling default fallback and pruning closed channels safely.
Code
package main
import (
"fmt"
"reflect"
"sort"
)
func main() {
channels := make([]chan string, 3)
for i := range channels {
channels[i] = make(chan string, 1)
}
cases := make([]reflect.SelectCase, 0, len(channels))
for _, ch := range channels {
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(ch),
})
}
// Non-blocking probe with SelectDefault before any message is sent
probe := make([]reflect.SelectCase, len(cases)+1)
copy(probe, cases)
probe[len(cases)] = reflect.SelectCase{Dir: reflect.SelectDefault}
chosen, _, _ := reflect.Select(probe)
fmt.Println("empty probe hit default:", probe[chosen].Dir == reflect.SelectDefault)
channels[0] <- "auth:ready"
channels[1] <- "billing:ready"
channels[2] <- "search:ready"
for _, ch := range channels {
close(ch)
}
var messages []string
for len(cases) > 0 {
idx, val, ok := reflect.Select(cases)
if !ok {
// Channel closed: drop its SelectCase so we stop selecting on it
cases = append(cases[:idx], cases[idx+1:]...)
continue
}
messages = append(messages, val.String())
}
sort.Strings(messages)
fmt.Println("drained sorted:", messages)
fmt.Println("remaining active cases:", len(cases))
}Step-by-step analysis — Multiplex Dynamic Channels With reflect.Select
The snippet is organized around the function main.
The loop for i := range channels is the only repeated construct.
Watch out for
- Zero packages pulled in — the runtime ships every API this code touches.
Putting it to use
Entry signature: func main()
The file’s steps show up in the output as empty probe hit default:, drained sorted:, remaining active cases:.
Core lines
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(ch),
})
for _, ch := range channels {
close(ch)
}
for i := range channels {
channels[i] = make(chan string, 1)
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Multiplex Dynamic Channels With reflect.Select print when run?
- Running the file directly is enough — expect labeled output lines such as `empty probe hit default:`, `drained sorted:`, `remaining active cases:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.