Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.TrySend()函数尝试在通道v 上发送x 但不会阻塞。要访问此函数,需要在程序中导入反射包。
Syntax:
Parameters: This function accept one parameter of Value type (x).
Return Value: This function returns whether the value was sent.
下面的例子说明了上述方法在 Golang 中的使用:
示例 1:
func (v Value) TrySend(x Value) bool
输出:
// 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())
}
示例 2:
true 1 1
输出:
// 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)
}