Go Fundamentals - Sample
Table of Contents
Chapter 11.4: Uni-Directional Channels
By default channels are bi-directional, meaning you can both send and receive data from the channel.
A common use for uni-directional channels is when you are passing a channel as an argument or receiving a channel as return value. This allows for control of the channel for the function/method and prevents outside callers from polluting the channel.
The standard library does this in the time
package with methods like time.Ticker
, Listing 11.1.
Understanding Uni-Directional Channels
Consider Listing 11.2. The Newspaper
contains a bi-directional channel, headlines chan string
, as a field. It also exposes two methods, TopHeadlines
and ReportStory
.
The TopHeadlines
method returns a read-only version of the headlines
channel that can be consumed by newspaper readers.
The ReportStory
method returns a write-only version of the headlines
channel that can be used by newspaper reporters to report their stories to the newspaper.
In both cases, Go, casts the bi-directional channel, headlines
, to the appropriate uni-directional channel returned by the method.