Home  >  Article  >  Backend Development  >  Can Go Channels Handle Multiple Data Types?

Can Go Channels Handle Multiple Data Types?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 13:55:30247browse

Can Go Channels Handle Multiple Data Types?

Type Agnostic Channels in Go

Question:

In Go, is it possible to send multiple types of data through a single channel?

Example:

The following code attempts to send different types through a channel: http://play.golang.org/p/7p2Bd6b0QT.

Answer:

Yes, it is possible to create type agnostic channels in Go. To send multiple types through a channel, use:

greet := make(chan pet)

With this modification, you can send any type that implements the pet interface.

Sending Generic Data:

If you need to send completely generic data, create a channel of type chan interface{} and use reflection to determine the type of data received.

Example:

ch := make(chan interface{})

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

ch <- "this is it"

Using a Type Switch:

As an alternative to reflection, you can use a type switch with a select statement like this:

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)
}

The above is the detailed content of Can Go Channels Handle Multiple Data Types?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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