RSS Amplifier

Ashraf Latif · Aug 5, 2025

Mastering Go 20: Channel Pipelines – Like Factory Assembly Lines!

0
Sign in to vote or save

Ashraf Latif · Ashraf Latif

“What if we could pass values step by step through a series of workers — like a mini-factory? Go can do that with channels!”

Let’s say you have a potato 🥔.

You want to:

  1. Peel it

  2. Slice it

  3. Fry it

Each step is done by a different worker. The potato goes from one worker to the next.

That’s exactly what a pipeline is in Go — and it’s super powerful!

We’ll build a pipeline with 3 stages:

  1. Generator – Creates numbers

  2. Doubler – Doubles each number

  3. Printer – Prints final result

Each stage runs in its own goroutine and talks via channels.

package main
import "fmt"
// Stage 1: Generate numbers
func generator(nums ...int) <-chan int {
  out := make(chan int)
  go func() {
    for _, n := range nums {
      out <- n
    }
    close(out)
  }()
  return out
}
// Stage 2: Double each number
func doubler(in <-chan int) <-chan int {
  out := make(chan int)
  go func() {
    for n := range in {
      out <- n * 2
    }
    close(out)
  }()
  return out
}
func main() {
  // Step 1: Start the generator
  numbers := generator(1, 2, 3, 4, 5)
  // Step 2: Send to doubler
  doubled := doubler(numbers)
  // Step 3: Print results
  for result := range doubled {
    fmt.Println(result)
  }
}
  • generator: Sends numbers to a channel

  • doubler: Reads from the input channel, doubles, sends to next

  • main: Reads final output and prints

Each step runs independently — like a real assembly line!

Term | Meaning
chan int | Channel that carries int values
<-chan int | Receive-only channel
chan<- int | Send-only channel
range in | Loop through incoming data
close(chan) | Close the channel when done sending
  • Clean structure: You can separate logic easily

  • Efficient: Each stage can run in parallel

  • Flexible: You can plug in or swap steps like Lego bricks 🧱

  • Add a tripler stage after doubler

  • Make a filter that only passes even numbers

  • Print stage with labels: "Result: 10"

Example:

func tripler(in <-chan int) <-chan int {
  out := make(chan int)
  go func() {
    for n := range in {
      out <- n * 3
    }
    close(out)
  }()
  return out
}

Then chain:

tripled := tripler(doubled)
  • Pipelines = multiple goroutines passing data

  • Channels connect each stage

  • Makes code modular, fast, and fun!

No posts

Read the original on ceghap.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.