I'm new to Golang and meet the strange behavior of Go's channel. The question is described as the following.
package main
import "fmt"
func main() {
ch := make(chan int)
fmt.Println("len:", len(ch))
fmt.Println("cap:", cap(ch))
fmt.Println("is nil:", ch == nil)
go func(ch chan int){
ch <- 233
}(ch)
fmt.Println(<- ch)
}
When I run the code above, I got result like this:
len: 0
cap: 0
is nil: false
233
The len and cap of the channel ch seem wierd but the code still works. But when I run this code:
package main
import "fmt"
func main() {
ch := make(chan int)
fmt.Println("len:", len(ch))
fmt.Println("cap:", cap(ch))
fmt.Println("is nil:", ch == nil)
ch <- 233 // Here changes!
fmt.Println(<- ch)
}
The result became: len: 0 cap: 0 is nil: false fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/tmp/sandbox640280398/main.go:12 +0x340
What's more, when I change the second code piece like the following: package main
import "fmt"
func main() {
ch := make(chan int, 1) //Here changes!
fmt.Println("len:", len(ch))
fmt.Println("cap:", cap(ch))
fmt.Println("is nil:", ch == nil)
ch <- 233
fmt.Println(<- ch)
}
Things worked again, I got:
len: 0
cap: 1
is nil: false
233
So, can anybody tell me the following questions:
Why make(chan int) return a channel with zero len and zero cap but still can work well in first code piece?
Why the second code use the channel in the main function instead of a new goroutine cause the deadlock?
Why I add a cap parameter to make in third code can fix the problem?
What's the difference between the channel(in 1st and 2nd code) with the nil channel?
Thanks!