当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Golang reflect.ChanOf()用法及代码示例


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

用法:
func ChanOf(dir ChanDir, t Type) Type

参数:此函数采用ChanDir类型(dir)和Type type(t)的三个参数。

返回值:此函数返回具有给定方向和元素类型的函数类型。

以下示例说明了以上方法在Golang中的用法:



范例1:

// 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)) 
}

输出:

chan<- int

范例2:

// 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) 
}

输出:

chan<- [5]int



相关用法


注:本文由纯净天空筛选整理自SHUBHAMSINGH10大神的英文原创作品 reflect.ChanOf() Function in Golang with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。