由于您从不关闭
ch通道,因此范围循环将永远不会结束。
您不能在同一频道上发送结果。一种解决方案是使用其他解决方案。
您的程序可以这样修改:
package mainimport ( "fmt")func total(in chan int, out chan int) { res := 0 for iter := range in { res += iter } out <- res // sends back the result}func main() { ch := make(chan int) rch := make(chan int) go total(ch, rch) ch <- 1 ch <- 2 ch <- 3 close (ch) // this will end the loop in the total function result := <- rch // waits for total to give the result fmt.Println("Total is ", result)}


