This is a creation in Article, where the information may have evolved or changed.
This blog has been migrated to www.0x520.com
Before using the channel practice encountered a problem, it seems as if the code is reasonable, and the compilation will not be a problem, but forget an important channel characteristics.
The correct code:
Package Mainimport "FMT" func foo () { defer FMT. PRINTLN ("World") FMT. Println ("Hello")}func sum (x, y int,c chan int) { c <-x + Y}func main () { foo () c: = make (chan int); Go sum (24,18,c) FMT. Println (<-c);}
If I change the code to:
Package Mainimport "FMT" func foo () { defer FMT. PRINTLN ("World") FMT. Println ("Hello")}//func sum (x, y int,c chan int) {// c <-x + Y//}func main () { foo ()/ c: = make (chan int); / Go sum (24,18,c)// FMT. Println (<-c); c: = make (chan int) D: = 2 c <-d+3 FMT. Println (<-C)}
Or
Package Mainimport "FMT" func foo () { defer FMT. PRINTLN ("World") FMT. Println ("Hello")}func sum (x, y int,c chan int) { c <-x + Y}func main () { foo () c: = make (chan int); SUM (24,18,c) FMT. Println (<-c);}
The following error will occur:
Helloworldfatal Error:all Goroutines is asleep-deadlock!goroutine 1 [Chan Send]:main.main () /users/john/a1.go : +0x60exit Status 2
This is why, seemingly reasonable procedures, is to ignore the channel is blocked, if not using the Go channel has been blocking the state, execution is dead loop. This feature is also convenient for many occasions.