Type Agnostic Channels in Go
Question:
Can multiple distinct data types be sent over a single generic channel in Go?
Answer:
Yes, it is possible. Using an example provided in a playground link, a channel can be created using the following syntax: greet: make(chan pet); then, any type that implements the pet interface can be seamlessly sent through this channel.
To achieve complete type agnosticism, a channel of type chan interface{} can be used. When receiving a value from such a channel, reflection can be employed to determine its type.
Example:
A simplified example (although potentially not idiomatic) demonstrating this concept:
<code class="go">ch := make(chan interface{}) go func() { select { case p := <-ch: fmt.Printf("Received a %q", reflect.TypeOf(p).Name()) } }() ch <- "this is it"</code>
Improved Example:
An alternative approach suggested by BurntSushi5 uses a type switch:
<code class="go">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) }</code>
The above is the detailed content of Is Go\'s Channel Type Agnostic?. For more information, please follow other related articles on the PHP Chinese website!