×

go · level 3 · unit 5 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A joins stages with channels, like a factory line.

A pipeline is a chain of stages joined by channels. Each is a goroutine that receives from the channel before it, does one small job and sends the result on. Like a factory line, every stage can be busy at the same time with a different item.

The rule that keeps it tidy: each stage ranges over its input and closes its output when the input runs dry. The close then flows down the line, stage by stage, until the last loop in main ends.

A parameter can hold a function, like f func(string) string below. So one stage can do any job you hand it, such as strings.TrimSpace or strings.ToUpper.

package main
import (
	"fmt"
	"strings"
)
func stage(in <-chan string, f func(string) string) <-chan string {
	out := make(chan string)
	go func() {
		defer close(out)
		for s := range in {
			out <- f(s)
		}
	}()
	return out
}
func main() {
	src := make(chan string, 2)
	src <- "  tea "
	src <- " cake"
	close(src)
	for s := range stage(stage(src, strings.TrimSpace), strings.ToUpper) {
		fmt.Println(s)
	}
}

defer close(out) closes the output however the goroutine ends.