Go language learning: what is Channel?

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

What is the channel?

In the Go language, the channel refers to the type of channels. It is sometimes used to refer directly to a channel that can pass a value of some kind.

Type notation

    • Chan T

      • The keyword Chan represents the keyword for the channel type, and T represents the element type of the channel type.
      • For example: type Intchan chan int alias type Intchan represents a channel type with an element type of int. We can directly declare a variable of type Chan int: var intchan chan int, after being initialized, the variable Intchan can be used to pass an element value of type int.
    • chan<-T

      • Can only be used to send a value, <-represents the Send operator
    • <-chan T
      • Receive channel value, <-represents the receive operator

Value notation

Properties and basic operations

    • Channel-based communication is an important means of synchronizing between multiple goroutine. The operation for the channel itself is also synchronous.
    • At the same time, only one goroutine can send element values to a channel
    • There is also only one goroutine that can receive element values from it.
    • The channel is equivalent to a FIFO first-out message queue.
    • The element values in the channel are atomic. They are not to be divided. Each element in the channel can only be received by one goroutine. The value of the element that has been received is immediately removed from the channel.

Initialize Channel

Make (chan int, 10)
The ~ expression Initializes a value for a channel type. The first argument passed to the Make function indicates that the specific type of this value is a channel type with an element type of int, while the second parameter refers to a value that can hold up to 10 element values at the same time.

 PackageMainImport("FMT")typePersonstruct{NamestringAgeuint8Address ADDR}typeAddrstruct{CitystringDistrictstring}funcMain () {Persionchan: = Make(ChanPerson, 1) P1: = person{"Harry.",, addr{"Shanxi","Xian"}} FMT. Printf ("P1 (1):%v\n", p1) Persionchan <-p1 p1. Address.district ="Shijingshan"Fmt. Printf ("P2 (2):%v\n", p1) P1_copy: = <-persionchan fmt. Printf ("p1_copy:%v\n", P1_copy)}
#go test.go(1): {Harry 32(2): {Harry 32 {Shanxi shijingshan}}p1_copy: {Harry 32 {Shanxi Xian}}

The element values in the channel are unaffected by the outside world. This shows that the element values that are made during the send process are fully replicated. This also guarantees the invariance of the values we pass with the channel.

Close Channel

Close (Strchan)
We should make it clear that the channel should not be closed at the receiving end, no matter what. Because there is no way to tell if the sending side will also send element values to the channel.

 PackageMainImport("FMT"    "Time")funcMain () {ch: = Make(Chan int,5) Sign: = Make(Chan int,2)Go func() { forI=0; I<5; i++ {ch <-i time. Sleep(1* Time. Second)}Close(CH) fmt. Println ("The channel is closed.") Sign <-0}()Go func() { for{e, OK: = <-ch fmt. Printf ("%d (%v) \ n", E,ok)if!ok { Break} time. Sleep(2* Time. Second)} FMT. Println ("done.") Sign <-1} () <-sign <-sign}

Operation Result:
0 (TRUE)
1 (true)
2 (True)
The channel is closed.
3 (True)
4 (True)
0 (FALSE)
Done.

The runtime system does not immediately take false as the second result of the corresponding receive operation after the channel CH is closed, but waits until the receiving end has received all the element values in the channel before doing so. This ensures that the security of the channel is closed on the sending side.

Not to be continued

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.