go / expert
Snippet
Dynamic Multi-Channel Multiplexing via Dynamic Runtime Reflection Select Cases
When the number of channels to receive from is dynamically determined at runtime, static select blocks are insufficient. This code uses reflect.Select to construct dynamic select cases programmatically, allowing arbitrary fan-in aggregation across variadic slice channels.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package mainimport ("reflect")type MultiResult struct {Index intValue anyOk bool}func MultiplexChannels(chans []chan any) MultiResult {cases := make([]reflect.SelectCase, len(chans))for i, ch := range chans {cases[i] = reflect.SelectCase{Dir: reflect.SelectRecv,Chan: reflect.ValueOf(ch),}}chosen, recv, ok := reflect.Select(cases)var val anyif recv.IsValid() {val = recv.Interface()}return MultiResult{Index: chosen, Value: val, Ok: ok}}
Breakdown
1
cases[i] = reflect.SelectCase{ Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ch) }
Builds a reflection select case specifying receive mode and the underlying channel Value.
2
chosen, recv, ok := reflect.Select(cases)
Blocks until one of the dynamically prepared channels yields a value or closes, returning the winning case index.