📜  Golang 中的reflect.ChanOf()函数示例

📅  最后修改于: 2021-10-25 02:27:48             🧑  作者: Mango

Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang中的reflect.ChanOf()函数用于获取给定方向和元素类型的通道类型,即t表示int,ChanOf(RecvDir, t)表示<-chan int。要访问此函数,需要在程序中导入反射包。

下面的例子说明了上述方法在 Golang 中的使用:

示例 1:

func ChanOf(dir ChanDir, t Type) Type

输出:

// Golang program to illustrate
// reflect.ChanOf() Function 
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function 
func main() {
  
    var k = reflect.TypeOf(0)
      
    // use of ChanOf method
    fmt.Println( reflect.ChanOf(reflect.SendDir, k))
}

示例 2:

chan<- int

输出:

// Golang program to illustrate
// reflect.ChanOf() Function 
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function 
func main() {
  
    ta := reflect.ArrayOf(5, reflect.TypeOf(123))
      
    //use of ChanOf method
    tc := reflect.ChanOf(reflect.SendDir, ta)
      
    fmt.Println(tc)
}