Using Go 1.23 Iterators in CLI Applications
· go
Go 1.23 shipped range-over-function iterators and the iter package, and they are a better fit than channels for streaming status updates out of a long-running CLI task. This post walks through a small example and then what happens under the hood.
Go CLI tools keep hitting the same wall. You have a long-running task, you want to stream status updates to the terminal, and now you’re staring at a channel, a goroutine, a select block, and a done signal that you will absolutely forget to close at least once.
Channels are genuinely great concurrency primitives. But reaching for them when you don’t actually need concurrency? That’s cargo-culted complexity.
The CLI I was building performs a long-running task and prints status updates as it goes (start, progress, error, done). These are simple requirements and the kind of thing that shouldn’t require you to think about goroutine lifecycles. Here is how iterators make this cleaner.
Defining Event Types
First, a straightforward EventType with one constant for each kind of event:
type EventType string
const (
EventTypeStart EventType = "start"
EventTypeUpdate EventType = "update"
EventTypeEnd EventType = "end"
EventTypeError EventType = "error"
)And a struct to carry the data:
type CommandEvent struct {
Type EventType
Message string
}Nothing fancy, just typed strings and a struct. Moving on.
A Custom Iterator Type
Here’s where it gets interesting:
type CommandEventIterator func(yield func(*CommandEvent, error) bool)One line, and that is your entire streaming abstraction. It is a function that yields *CommandEvent values and errors, one at a time, directly into a for...range loop. No channels. No goroutines. No close signals.
Why does this matter? Because the calling code does not need to know anything about how events are produced, it just ranges over them. The iterator owns the control flow, yields when it has something and stops when it’s done.
The Iterator Function
Here’s the implementation, which simulates a task with progress updates and an error at 60%:
func CommandEventStream() CommandEventIterator {
return func(yield func(*CommandEvent, error) bool) {
// Start event
if !yield(&CommandEvent{
Type: EventTypeStart,
Message: "Task started",
}, nil) {
return
}
// Simulate task with possible error
for i := 1; i <= 5; i++ {
time.Sleep(2 * time.Second)
// Simulate an error at 60%
if i == 3 {
if !yield(nil, fmt.Errorf("an error occurred at %d%% progress", i*20)) {
return
}
continue
}
// Update event
if !yield(&CommandEvent{
Type: EventTypeUpdate,
Message: fmt.Sprintf("Task progress: %d%%", i*20),
}, nil) {
return
}
}
// End event
if !yield(&CommandEvent{
Type: EventTypeEnd,
Message: "Task completed",
}, nil) {
return
}
}
}Look, the if !yield(...) { return } pattern takes a minute to internalize. But once you do, it reads like a script that emits start, loops through updates, handles the error case and emits end. The yield returns false when the consumer breaks out of the loop, and you just… return. That’s the entire cancellation mechanism.
Consuming It
The consumer side is where this pattern pays off:
func main() {
fmt.Println("Starting the CLI application with error handling...")
for event, err := range CommandEventStream() {
if err != nil {
fmt.Println("Error:", err)
continue
}
switch event.Type {
case EventTypeStart:
fmt.Println("Start:", event.Message)
case EventTypeUpdate:
fmt.Println("Update:", event.Message)
case EventTypeEnd:
fmt.Println("End:", event.Message)
}
}
fmt.Println("CLI application has finished.")
}A for...range loop. That’s it. There are no channel reads, no goroutine cleanup, no deferred closes and no sync.WaitGroup. You just iterate over events and handle them. The iterator and the loop run in the same goroutine, so there’s zero concurrency overhead.
Running it prints this:
Starting the CLI application with error handling...
Start: Task started
Update: Task progress: 20%
Update: Task progress: 40%
Error: an error occurred at 60% progress
Update: Task progress: 80%
Update: Task progress: 100%
End: Task completed
CLI application has finished.The progress lines arrive two seconds apart (that’s the time.Sleep in the producer), and the start and end events print right away. That is streaming output with no buffering, no memory accumulation and no concurrency bugs waiting to surface in production.
Why This Is Better
There are four reasons:
- Only one event is in memory at a time. It is not a slice of all events and it is not a buffered channel.
- The producer reads top-to-bottom like a script, and the consumer is a plain loop.
- Errors flow through the same yield mechanism, so there’s no separate error channel.
- There is no concurrency tax. It is the same goroutine and the same stack, and you don’t pay for what you don’t use.
How many times have you seen a channel-based approach where someone forgot to drain the channel or didn’t close it or introduced a deadlock because the producer and consumer had different assumptions about buffering? Iterators eliminate that entire category of bug.
Under the Hood
If you only want to use iterators, skip this section.
A range-over-func loop is plain function calls. The compiler turns the loop body into a yield function and passes it to the iterator. Each call to yield runs the loop body once with the values you passed, and yield returns false when the loop exits early (a break or a return), so the iterator must stop. Calling yield again after that panics. It all runs in the same goroutine on the same stack, with no scheduling and no hidden concurrency.
The CommandEventIterator type above has the same shape as iter.Seq2[*CommandEvent, error], so you can use the standard type instead of declaring your own.
Python generators and C# enumerators solve the same problem, but they are pull iterators, where the caller asks for each value. Go’s iterators push values into the loop, and iter.Pull turns one into a pull iterator when you need that. And it’s Go, so it compiles to a single binary and runs without a runtime interpreter. That combination of ergonomics and performance is genuinely hard to find.
Full Code Example
Here’s the entire main.go file for reference:
package main
import (
"fmt"
"time"
)
// EventType represents the type of event.
type EventType string
const (
EventTypeStart EventType = "start"
EventTypeUpdate EventType = "update"
EventTypeEnd EventType = "end"
EventTypeError EventType = "error"
)
// CommandEvent represents an event during the execution of a command.
type CommandEvent struct {
Type EventType
Message string
}
// CommandEventIterator is a custom iterator type for CommandEvent and error.
type CommandEventIterator func(yield func(*CommandEvent, error) bool)
// CommandEventStream returns a CommandEventIterator.
// It simulates a long-running process that yields command events over time.
func CommandEventStream() CommandEventIterator {
return func(yield func(*CommandEvent, error) bool) {
// Start event
if !yield(&CommandEvent{
Type: EventTypeStart,
Message: "Task started",
}, nil) {
return
}
// Simulate task with possible error
for i := 1; i <= 5; i++ {
time.Sleep(2 * time.Second)
// Simulate an error at 60%
if i == 3 {
if !yield(nil, fmt.Errorf("an error occurred at %d%% progress", i*20)) {
return
}
continue
}
// Update event
if !yield(&CommandEvent{
Type: EventTypeUpdate,
Message: fmt.Sprintf("Task progress: %d%%", i*20),
}, nil) {
return
}
}
// End event
if !yield(&CommandEvent{
Type: EventTypeEnd,
Message: "Task completed",
}, nil) {
return
}
}
}
func main() {
fmt.Println("Starting the CLI application with error handling...")
for event, err := range CommandEventStream() {
if err != nil {
fmt.Println("Error:", err)
continue
}
switch event.Type {
case EventTypeStart:
fmt.Println("Start:", event.Message)
case EventTypeUpdate:
fmt.Println("Update:", event.Message)
case EventTypeEnd:
fmt.Println("End:", event.Message)
}
}
fmt.Println("CLI application has finished.")
}Go 1.23’s iterators aren’t flashy and they don’t require framework buy-in. They just give you a clean way to stream values through a for...range loop. For CLI tools that need to report progress, handle errors inline and stay readable six months later, this pattern replaces channels, callbacks and hand-rolled state machines with a loop.
Use the loop until you actually need concurrency.