I've spent pretty significant amount of time trying to debug why my channel doesn't accept anything. I managed to localize the issue as the one related to the scope of named return values when they are returned with naked returns. The below code shows the problem.
package main
import (
"log"
"sync"
)
var receiver chan int
func Setup() (receiver chan int) {
receiver = make(chan int)
return
}
//func Setup() (chan int) {
// receiver = make(chan int)
// return receiver
//}
func Launch(j int){
for i := 0; i < j; i++ {
receiver <- i
}
}
func main() {
var wg sync.WaitGroup
wg.Add(10)
rcvr := Setup()
go func() {
for r := range rcvr {
log.Println(r)
wg.Done()
}
}()
Launch(10)
wg.Wait()
}
Running this code produces the next error
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send (nil chan)]:
...
I cannot grasp why the channel should be nil. I tried similar assignment with primitive values and it returns what I expect. Why is it nil with channels? What shadows what in here?