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

Can Go Channels Handle Multiple Data Types?

Mary-Kate Olsen
Release: 2024-11-03 13:55:30
Original
255 people have browsed it

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

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

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

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!

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