This is a created article in which the information may have evolved or changed.
Always try to follow the tutorial to understand the use of channel and the significance of specific existence. According to the personal understanding, the channel is mainly used to achieve data synchronization and interaction between different goroutine.
Basic knowledge of channel:
Channel is a type of pipe that can be sent or received with the channel operator <-.
CH <-V//V is fed into channel ch.
V: = <-ch//is received from CH and assigned to V.
(the arrow is the direction of the data flow.) )
Like map and slice, the channel must be created before it is used:
CH: = make (chan int)
By default, both send and receive are blocked until the other end is ready. This allows the goroutine to synchronize without a definite lock or race variable.
The code is as follows:
Package Mainimport "FMT" func sum (a []int, C Chan int) {sum: = 0for _, V: = range a {sum + = v}c <-sum//Send sum to C} Func Main () {a: = []int{7, 2, 8,-9, 4, 0}c: = make (chan int) go sum (A[:len (a)/2], C) Go sum (A[len (a)/2:], c)/* The code below will ensure that until two RO Utine result output to C, continue to execute, so as to achieve the effect of synchronization */x, y: = <-c/* The first channel is filled after the assignment */, <-C/* The second channel is filled after the assignment */ FMT. Println (x, Y, X+y)}