Golang reflect.TrySend()函数及示例

Golang reflect.TrySend()函数及示例

Go 语言提供了内置支持实现运行时反射,利用 reflect 包允许程序操作任意类型的对象。其中, reflect.TrySend() 函数尝试将 x 发送到通道 v 但不会阻塞。要使用此函数,需要在程序中导入 reflect 包。

语法:

func (v Value) TrySend(x Value) bool

参数: 此函数接受 Value 类型的一个参数 x。

返回值: 此函数返回值表示是否已经发送了该值。

下面的示例演示了在 Golang 中使用上述方法:

示例1:

// Golang 程序,演示 reflect.TrySend() 函数
package main
import (
    "fmt"
    "reflect"
)
func main() {
    c := make(chan int, 1)
    vc := reflect.ValueOf(c)
    // 使用 TrySend() 方法
    succeeded := vc.TrySend(reflect.ValueOf(123))
    fmt.Println(succeeded, vc.Len(), vc.Cap())
}

输出:

true 1 1

示例2:

// Golang 程序,演示 reflect.TrySend() 函数
package main
import (
    "fmt"
    "reflect"
)
func main() {
    c := make(chan int, 1)
    vc := reflect.ValueOf(c)
    // 使用 TrySend() 方法
    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()
    // 为了避免 panic,这一次删除了发送 case 分支。
    selIndex, _, sentBeforeClosed = reflect.Select(branches[:2])
    fmt.Println(selIndex, sentBeforeClosed)
}

输出:

true 1 1
1
true
123
1 false

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程