Home > Backend Development > Golang > Is Go\'s Channel Type Agnostic?

Is Go\'s Channel Type Agnostic?

Linda Hamilton
Release: 2024-11-04 13:00:29
Original
678 people have browsed it

Is Go's Channel Type Agnostic?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template