Type agnostic channels in go

20,271

Yes, it's possible. For example in your code you could just use:

greet: make(chan pet)

And then you would be able to send seamlessly anything that implements type pet interface.

If you want to send something completely generic you can use a chan interface{} and then use reflect to find out what it is when you receive something.


A dumb - and probably not idiomatic - example:

ch := make(chan interface{})

go func() {
    select {
    case p := <-ch:
        fmt.Printf("Received a %q", reflect.TypeOf(p).Name())
    }
}() 
ch <- "this is it"

As BurntSushi5 points out, a type switch is better:

p := <-ch
switch p := p.(type) {
case string:
    fmt.Printf("Got a string %q", p)
default:
    fmt.Printf("Type of p is %T. Value %v", p, p)
}
Share:
20,271
ben lemasurier
Author by

ben lemasurier

Updated on May 27, 2020

Comments

  • ben lemasurier
    ben lemasurier almost 4 years

    I'm still sort of wrapping my head around interfaces within golang. Is it possible to send multiple different types over a single, "generic" channel?

    Here's a very simple example: http://play.golang.org/p/7p2Bd6b0QT.

  • BurntSushi5
    BurntSushi5 about 10 years
    I think in general, you'll want to use a type switch before resorting to reflection. To get the type name, you can use the formatting option %T with the value. No reflect needed.
  • cnicutar
    cnicutar about 10 years
    @BurntSushi5 Thank you for your comment!