Original author, public number [programmer reading], welcome to pay attention to the public number, reprint the article please indicate the source oh.

Go language is native to support concurrent programming, and Channel is the Go language to achieve concurrency indispensable type, let’s learn.

What is the channel

We know that Gotoutine is the concurrency execution unit in Go language. We can create multiple Goroutine programs to realize concurrency, and the communication mechanism between Goroutine is realized by channel.

A channel is a special type in the Go language. We can declare what type a channel can send, and then send or receive values to the channel to reach the destination of the communication.

The creation of a channel

Declare a channel variable using the keyword chan followed by a datatype that can be sent, as shown below

var ch chan int
Copy the code

Channel is a reference type, so the initial value of the declared channel but uninitialized variable is nil. Sending a value to an uninitialized channel type causes panic, so you can initialize a channel using the make method

ch = make(chan int)
Copy the code

A channel initialized by the make method references the underlying data structure. Channels of the same type can be compared for equality. If they reference the same underlying structure, they are equal. All channel types can be compared to nil.

Send and receive operations

The purpose of a channel is to communicate, so there are two operations on a channel, send and receive, sending values in one gotoutine and receiving values in the other goroutine, to achieve the purpose of sharing memory in communication.

package main
import "fmt"

func main() {
    ch := make(chan int)
    go func() {
        for i := 0; i < 10; i++ {
            ch <- i
        }
        close(ch)
    }()
    for {
        x ,ok := <- ch
        if! ok{break
        }
        fmt.Println(x)
    }
}

Copy the code

In the example above, we used the anonymous function to create a Gotourine that sends 10 values to CH and receives them in the main Goroutine. After sending, Coco uses the close() function to close the channel.

Note that sending a value to a closed channel raises a Pannic error. If you receive a value from a closed channel, you will always receive a zero value for that data type. The Go language does not determine whether a channel is closed, but it can accept a second bool to determine whether a valid value has been obtained. In the example above, Ok is used to represent this value.


Your attention is the biggest encouragement on my writing road!