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.

$ go doc time.Ticker

package time // import "time"

type Ticker struct {
	C <-chan Time // The channel on which the ticks are delivered.
	// Has unexported fields.
}
    A Ticker holds a channel that delivers “ticks” of a clock at intervals.

func NewTicker(d Duration) *Ticker
func (t *Ticker) Reset(d Duration)
func (t *Ticker) Stop()

--------------------------------------------------------------------------------
Go Version: go1.22.0

Listing 11.1: The time.Ticker function.

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.

type Newspaper struct {
	headlines chan string
	quit      chan struct{}
}

// TopHeadlines returns a read-only channel of strings
// that represent the top headlines of the newspaper.
// This channel is consumed by newspaper readers.
func (n Newspaper) TopHeadlines() <-chan string {
	return n.headlines
}


// ReportStory returns a write-only channel of strings
// that a reporter can use to report a story.
func (n Newspaper) ReportStory() chan<- string {
	return n.headlines
}
Listing 11.2: The Newspaper type.

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.


Subscribe to our newsletter