This is a creation in
Article, where the information may have evolved or changed.
PackageMainImport("FMT")funcMain() {//case 1: Writing to a nil channel will block.//var C Chan int//go language automatically assigns 0 values of its type to uninitialized variables, such as nil, 0, "" and so on.//c <-1//case 2: Reading a nil channel will block.//<-C//case 3: A panic exception will occur when writing to a unbuffered channel that has been closed.//C1: = make (chan int)//close (C1)//c1 <-1//case 4: Reads an already closed unbuffered channel, returning 0 values for the channel element type, such as: False,o,nil, etc.//x: = <-C1//fmt. PRINTLN (x)//case 5: Read the buffered channel that has been closed, see the following code comment. C2: = Make(Chanint, 3) C2 <-1 C2 <-2 C2 <-3 Close(C2)//Although the channel has been closed, we can still read the 3 values written before the shutdown, and return the 0 value corresponding to the Channel element type, since the 4th reading begins: 0,//Even if you continue to read continuously, the value is still 0. Fmt.Printf("%d\n", <-C2) fmt.Printf("%d\n", <-C2) fmt.Printf("%d\n", <-C2) fmt.Printf("%d\n", <-C2) fmt.Printf("%d\n", <-C2) fmt.Printf("%d\n", <-C2)//case 6: A panic exception will occur when writing to a buffered channel that has been closed. C2 <-4 //Major principle: 1. It is preferable for the producer or writer to close the channel, which effectively avoids panic anomalies.//2. The channel itself without buffering has two characteristics of communication synchronization, the channel is thread-safe, co-security, can be multiple goroutine shared use does not have to lock to protect it.}
Simple refinement, write code test a bit, afraid to forget to write down notes, thank you for referring to the article author, read its articles so that I benefited, in this expression thanks.
Note: This article is only my personal notes, if there are errors and omissions, please correct me, study together, my e-mail: htyu_0203_39@sina.com