Golang control the access port of the channel

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

Golang control the access port of the channel

We often use the channel to communicate data between multiple goroutine, but how do we write Chan as a function parameter? Maybe some people think this problem is silly, but this is really what I know today.

First, let's look at the following code:

funcMain () {c: = Make(Chan int)GoIn (c)GoOut (c) time. Sleep (time. Second)}funcIn (cChan int) { forI: =0; I <Ten; i++ {c <-i}Close(c) fmt. Println ("int End")}funcOut (cChan int) { forI: =RangeC {FMT. Printf ("%d\n", i)} fmt. Println ("Out End")}

This is nothing more than inserting 10 numbers into the channel in the In method, and then pulling out the number in the Out method (yes, you're right, range can be used to take a value from the channel).

If I want to give out the method to the third party to achieve, but I need to output the order of the numbers in strict accordance with my order, that is, I need to explicitly stipulate that the out method can only be taken from the channel value, not to assign a value in the channel, this time we should follow the following way to write

typeinterface{    Out(c <-chanint)}

Once in the implementation of this out method to the Chan inserted value, it will not even compile (exclamation of the rigorous go, the design of the Great God is classic), so that we can use the method to restrict the access to the channel data direction, then if you want to limit Chan can only insert can not read how should be written?

typeinterface{    Out(c <-chanint)        chanint)}

Based on this way we can prevent Chan from exposing the data in the design process to control the access, of course, you do not write "<-" on the parameters, the channel is a full-duplex channel, depending on the business you need to write, but can limit the limit, Developing good coding habits should start with these details.

Related Article

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.