我正在尝试编写这样的函数,但我不能声明切片的通道
func fanIn(set <-[]chan string) <-chan string {
c := make(chan string)
for i := range set {
go func() { for {c <-set[i]} }()
}
return c
}
Run Code Online (Sandbox Code Playgroud)
Go有可能将一片频道作为参数吗?
通话的例子
set := [2]chan string{mylib.Boring("Joe"), mylib.Boring("Ann")}
c := fanIn(set)
Run Code Online (Sandbox Code Playgroud)
如果我能做到这一点
func fanIn(input1, input2 <-chan string) <-chan string {
Run Code Online (Sandbox Code Playgroud)
我假设应该可以有"<-chan string"的切片或数组
更新:
func fanIn(set []<-chan string) <-chan string {
c := make(chan string)
for i := range set {
go func() {
for {
x := <-set[i]
c <- x
}
}()
}
return c
}
func main() {
set := []<-chan string{mylib.Boring("Joe"), mylib.Boring("Ann"), mylib.Boring("Max")}
c := fanIn(set)
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
fmt.Println("You're boring: I'm leaving.")
}
Run Code Online (Sandbox Code Playgroud)
我稍微修复了函数中的语法,它现在可以编译:
func fanIn(set []<-chan string) <-chan string {
c := make(chan string)
for i := range set {
// here is the main change - you receive from one channel and send to one.
// the way you wrote it, you're sending the channel itself to the other channel
go func() { for {c <- <- set[i]} }()
}
return c
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,为了可读性,我将其写为:
go func() {
for {
x := <-set[i]
c <- x
}
}()
Run Code Online (Sandbox Code Playgroud)
set[i]编辑:您的原始代码在 goroutine 内部使用时存在问题,导致它们全部从最后一个通道读取。这是一个固定版本:
func fanIn(set []<-chan string) <-chan string {
c := make(chan string)
for i := range set {
go func(in <-chan string) {
for {
x := <- in
c <- x
}
}(set[i])
}
return c
}
Run Code Online (Sandbox Code Playgroud)