How can I declare a chan (channels) fragment in func

I am trying to write such a function, but I cannot declare a channel fragment

func fanIn(set <-[]chan string) <-chan string { c := make(chan string) for i := range set { go func() { for {c <-set[i]} }() } return c } 

Is it possible in Go to have a slice of channels as an argument?

call example

 set := [2]chan string{mylib.Boring("Joe"), mylib.Boring("Ann")} c := fanIn(set) 

if i can do it

 func fanIn(input1, input2 <-chan string) <-chan string { 

I suppose it should be possible to have a slice or array "<-chan string"

update:

 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.") } 
+5
source share
1 answer

I have slightly corrected the syntax in your function, now it compiles:

 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 } 

By the way, for the sake of readability, I would write it as:

  go func() { for { x := <-set[i] c <- x } }() 

EDIT: your source code had a problem using set[i] inside goroutine, forcing them all to read from the last channel. here is the fixed version:

 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 } 
+4
source

Source: https://habr.com/ru/post/1204405/


All Articles