Golang: iter MORE!
iter.Seq is like a Unix pipe for Go code - lazy, composable, and surprisingly powerful. And the best part? It’s really just a function.
Do you still remember from the previous post that iter.Seq is a type alias for a function?
So, I might repeat myself:
type Seq[T] = func(yield func(T) bool)IT’S A FUNCTION!!!
If it’s a function, you can do many interesting things with it, such as writing your own Map:
func Map[T any](xs iter.Seq[T], mapper func(T) T) iter.Seq[T] {
return func(yield func(T) bool) {
for x := range xs {
tmp := mapper(x)
if !yield(tmp) {
return
}
}
}
}Or even add Filter:
func Filter[T any](xs iter.Seq[T], filter func(T) bool) iter.Seq[T] {
return func(yield func(T) bool) {
for x := range xs {
if !filter(x) {
continue
}
if !yield(x) {
return
}
}
}
}It’s that simple. What we have here are higher-order functions -Map and Filter.
With these, we could even recreate our own version of lo!
But let’s get back to the main point: what’s the best thing you can do with functions?
Get Mike’s stories in your inbox
Join Medium for free to get updates from this writer.
Function composition (pipelining):
xs := []int{1, 2, 3, 4, 5, 6}
// Square each element
ms := Map(slices.Values(xs), func(x int) int { return x * x })
// Keep only even numbers
fs := Filter(ms, func(x int) bool { return x%2 == 0 })Here we chain Map and Filter together - the output of one becomes the input to the next. This is the essence of functional composition: building complex transformations by combining simple building blocks.
And for dessert - terminators (functions that consume the sequence):
func Reduce[T any](xs iter.Seq[T], zero T, acc func(T, T) T) T {
for x := range xs {
zero = acc(zero, x)
}
return zero
}The Takeaway
type Seq[T] = func(yield func(T) bool)It’s just a function. But because it’s a function, we get:
- Lazy evaluation — compute only what you need
- Composability — build complex pipelines from simple pieces
- Zero allocations — no intermediate slices, no memory overhead
- Infinite sequences — generate values on the fly
- First-class citizenship — pass them around, return them, store them



