Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.TrySend() Function in Golang attempts to send x on the channel v but will not block. To access this function, one needs to imports the reflect package in the program.
C
Output:
C
Output:
Syntax:Below examples illustrate the use of the above method in Golang: Example 1:func (v Value) TrySend(x Value) boolParameters: This function accept one parameter of Value type (x). Return Value: This function returns whether the value was sent.
// Golang program to illustrate
// reflect.TrySend() Function
package main
import (
"fmt"
"reflect"
)
func main() {
c := make(chan int, 1)
vc := reflect.ValueOf(c)
// use of TrySend() method
succeeded := vc.TrySend(reflect.ValueOf(123))
fmt.Println(succeeded, vc.Len(), vc.Cap())
}
true 1 1Example 2:
// Golang program to illustrate
// reflect.TrySend() Function
package main
import (
"fmt"
"reflect"
)
func main() {
c := make(chan int, 1)
vc := reflect.ValueOf(c)
// use of TrySend() method
succeeded := vc.TrySend(reflect.ValueOf(123))
fmt.Println(succeeded, vc.Len(), vc.Cap())
vSend, vZero := reflect.ValueOf(789), reflect.Value{}
branches := []reflect.SelectCase{
{Dir: reflect.SelectDefault, Chan: vZero, Send: vZero},
{Dir: reflect.SelectRecv, Chan: vc, Send: vZero},
{Dir: reflect.SelectSend, Chan: vc, Send: vSend},
}
selIndex, vRecv, sentBeforeClosed := reflect.Select(branches)
fmt.Println(selIndex)
fmt.Println(sentBeforeClosed)
fmt.Println(vRecv.Int())
vc.Close()
// Remove the send case branch this time,
// for it may cause panic.
selIndex, _, sentBeforeClosed = reflect.Select(branches[:2])
fmt.Println(selIndex, sentBeforeClosed)
}
true 1 1 1 true 123 1 false