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.