Search code examples
gochannelreflect

How to get type of chan with reflect package


Say I have a chan in Go:

var c = make(chan int)

how can discover that it's a channel using:

var isChannel = reflect.ValueOf(c).Kind() == reflect.Chan

but does anyone know how I determine the type of the channel, in this case int?


Solution

  • Use Elem to get the channel type:

    var isChannel = reflect.ValueOf(c).Kind() == reflect.Chan
    channelType := reflect.ValueOf(c).Type().Elem()
    

    For an int channel, channelType will be int.