Golang reflect.ChanDir type example

package reflect

Golang reflect.ChanDir type usage example

 package main

 import (
  "fmt"
  "reflect"
 )

 func main() {
  var a chan<- int
  var typeA reflect.Type = reflect.TypeOf(a)

  fmt.Println("Channel A type is : ", typeA.ChanDir().String())
  fmt.Println("Is channel A - send direction only ? : ", typeA.ChanDir() == reflect.SendDir)

  fmt.Println("--------------------------------------------------------------")

  var b <-chan int
  var typeB reflect.Type = reflect.TypeOf(b)
  fmt.Println("Channel B type is : ", typeB.ChanDir().String())
  fmt.Println("Is channel B - send direction only ? : ", typeB.ChanDir() == reflect.SendDir)
  fmt.Println("Is channel B - receive direction only ? : ", typeB.ChanDir() == reflect.RecvDir)

  fmt.Println("--------------------------------------------------------------")

  var c chan int
  var typeC reflect.Type = reflect.TypeOf(c)
  fmt.Println("Channel C type is : ", typeC.ChanDir()) // without String()
  fmt.Println("Is channel C - send direction only ? : ", typeC.ChanDir() == reflect.SendDir)
  fmt.Println("Is channel C - receive direction only ? : ", typeC.ChanDir() == reflect.RecvDir)
  fmt.Println("Is channel C - both send receive direction? : ", typeC.ChanDir() == reflect.BothDir)

 }

Output :

 Channel A type is :  chan<-
 Is channel A - send direction only ? :  true
 --------------------------------------------------------------
 Channel B type is :  <-chan
 Is channel B - send direction only ? :  false
 Is channel B - receive direction only ? :  true
 --------------------------------------------------------------
 Channel C type is :  chan
 Is channel C - send direction only ? :  false
 Is channel C - receive direction only ? :  false
 Is channel C - both send receive direction? :  true

SEE ALSO : https://www.socketloop.com/tutorials/golang-channels-and-buffered-channels-examples

Advertisement