I am go newbie and trying to understand channels. Why does following go snippet deadlocks(fatal error: all goroutines are asleep – deadlock!) even though there are two routines working with given channel?
package main
import "fmt"
var helloChan chan int
func main() {
fmt.Printf("%T\n", helloChan)
go func() {
helloChan <- 42
}()
fmt.Println("got from chan: ", <-helloChan)
}
Following works and there is no additional goroutine. Only difference is how channel is created. The type is same in both case though.
package main
import "fmt"
func main() {
helloChan := make(chan int)
fmt.Printf("%T\n", helloChan)
go func() {
helloChan <- 22
}()
fmt.Println("got from chan: ", <-helloChan)
}
>Solution :
In the first example you never created the channel, the helloChan variable is nil. If you update it to create the channel it’ll work the same as the second one.
package main
import "fmt"
var helloChan chan int
func main() {
helloChan = make(chan int)
fmt.Printf("%T\n", helloChan)
go func() {
helloChan <- 42
}()
fmt.Println("got from chan: ", <-helloChan)
}