Go中的类型不可知通道(Type agnostic channels in go)

huangapple go评论74阅读模式
英文:

Type agnostic channels in go

问题

我正在努力理解Golang中的接口。是否可以通过一个“通用”通道发送多个不同类型的数据?

这是一个非常简单的例子:http://play.golang.org/p/7p2Bd6b0QT

英文:

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.

答案1

得分: 36

是的,这是可能的。例如,在你的代码中,你可以简单地使用:

greet: make(chan pet)

然后,你就可以无缝地发送任何实现了 type pet interface 的内容。

如果你想发送一些完全通用的内容,你可以使用 chan interface{},然后在接收到内容时使用 reflect 来找出它是什么。


一个愚蠢的 - 也许不是惯用的 - 示例:

ch := make(chan interface{})

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

正如 BurntSushi5 指出的,类型切换更好:

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)
}
英文:

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 := &lt;-ch:
        fmt.Printf(&quot;Received a %q&quot;, reflect.TypeOf(p).Name())
    }
}()	
ch &lt;- &quot;this is it&quot;

As BurntSushi5 points out, a type switch is better:

p := &lt;-ch
switch p := p.(type) {
case string:
    fmt.Printf(&quot;Got a string %q&quot;, p)
default:
    fmt.Printf(&quot;Type of p is %T. Value %v&quot;, p, p)
}

huangapple
  • 本文由 发表于 2014年2月28日 08:06:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/22083490.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定