Created
April 27, 2017 07:47
-
-
Save lummie/c1600570882fc042ed43c4aa0447356d to your computer and use it in GitHub Desktop.
Go Example - Channel that can receive any type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"reflect" | |
) | |
/* | |
This is an example of a channel that can receive any data type, e.g. different struct types | |
It shows how to use switch on the type of the data received in the channel to allow you | |
to change the logic based on the type | |
It shows how to use close() to close the channel when no more values are sent to it and how to shutdown the go routine | |
based on the channel still being open (isOpen) | |
Output: | |
2017/04/27 08:39:38 TypeA | |
2017/04/27 08:39:38 main.TypeB | |
*/ | |
func main(){ | |
ch := make(chan interface{}) // channel to receive any type | |
done := make(chan bool) // channel to wait for completion | |
// declare a couple of types | |
type TypeA struct{ | |
A int | |
} | |
type TypeB struct{ | |
A int | |
} | |
// channel receiver | |
go func () { | |
for { | |
d, isOpen := <-ch // get data off chanel | |
switch d.(type) { // do different logic base on the type of the data | |
case TypeA: | |
log.Print("TypeA") | |
case TypeB: | |
log.Print(reflect.TypeOf(d)) | |
} | |
if !isOpen { // if the channel has been closed, signal done and exit go routine | |
done <- true | |
return | |
} | |
} | |
}() | |
// send instances of different types | |
ch <- TypeA{0} | |
ch <- TypeB{0} | |
close(ch) // close the channel as we are nto sending anything else | |
<- done // wait for go routine to finish | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment