I'm trying to use reflect.Select to send data in a channel. The code is as following.
c := make(chan int, 1)
vc := reflect.ValueOf(c)
go func() {
<-c
}()
vSend := reflect.ValueOf(789)
branches := []reflect.SelectCase{
{Dir: reflect.SelectSend, Chan: vc, Send: vSend},
}
selIndex, _, sentBeforeClosed := reflect.Select(branches)
fmt.Println(selIndex)
fmt.Println(sentBeforeClosed)
But I found it doesn't work, the result is
0
false
why do I get false? How could I monitor a list of channels which could recv data?
If you carefully read
reflect.Selectdocumentation, you'll see that the third return value is relevant only when the direction of thecaseis a receive operation.In other words, the above means that on receive operations the third return value will be
trueif the channel received an actual value, orfalseif it received the zero value for the channel item type due to the channel being closed.But your code uses
Dir: reflect.SelectSend. On send operations, it is not necessary to inspect the boolean value because the send case will either be selected or not. If it is, the first return valueselIndexwill be the index of the selected case, and that's all you need to know. The third return value in this case isfalsesimply because it is the zero value of thebooltype.If you change your code to use
Dir: reflect.SelectRecv, then the boolean value will have meaning, based on the above quoted documentation:Prints:
Playground: https://go.dev/play/p/ezuc_OaK_SW