[英]go function that accepts any channel
I would like to write a function in go that takes a generic channel as an input.我想在 go 中编写一个函数,它将通用通道作为输入。 I'd like it to be able to accept any channel regardless of what type that channel is for.
我希望它能够接受任何频道,而不管该频道是什么类型的。 I assumed I could us
func myFunc(channel chan interface{})
but I'm getting a compilation error when I try to pass my channel to it.我以为我可以
func myFunc(channel chan interface{})
但是当我尝试将我的频道传递给它时出现编译错误。 Is there a way to do this in go?有没有办法做到这一点?
chan interface{}
and chan int
are two distinct type definitions. chan interface{}
和chan int
是两个不同的类型定义。
Consider this example:考虑这个例子:
package main
import (
"fmt"
)
func myFunc(ch chan interface{}) {
fmt.Println("I'm called")
}
func main() {
ch := make(chan int)
myFunc(ch)
fmt.Println("Done")
}
This function panics with这个函数恐慌
cannot use ch (type chan int) as type chan interface {} in argument to myFunc
Let's change the type to chan interface{}
让我们将类型更改为
chan interface{}
package main
import (
"fmt"
)
func myFunc(ch chan interface{}) {
fmt.Println("I'm called")
}
func main() {
ch := make(chan interface{})
myFunc(ch)
fmt.Println("Done")
}
This compiles.这编译。
chan int
is used as an example - anything else apart from chan interface{}
as the type for ch
will result in a panic. chan int
为例 - 除了chan interface{}
之外的任何其他类型作为ch
的类型都会导致恐慌。
If you absolutely want a function that you want to be able to call with any of chan int
, chan string
, chan customtype
your only bet right now is to accept a plain interface{}
.如果您绝对想要一个能够使用
chan int
、 chan string
、 chan customtype
任何一个调用的函数,那么您现在唯一的选择就是接受一个普通的interface{}
。
As @mkopriva mentioned though, generics are coming soon.正如@mkopriva 提到的,泛型很快就会出现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.