liveBook · Manning

Push iterator

As explained in Go by Example

A push iterator is an iteration abstraction in which a producer invokes a consumer with each successive value rather than having the consumer request values.

A push iterator lets a producer deliver sequence values by calling a consumer-supplied yield function. The consumer does not request the next value; it receives each value as the iterator produces it. A boolean returned by yield tells the iterator whether to continue or stop. section 6.3.1

In Go, iter.Seq[V] represents this pattern as a function that accepts yield func(V) bool. Instantiating it as iter.Seq[Result] creates an iterator for Result values, while a named Results type gives the package API a domain-specific name. section 6.3.1

Streaming HTTP results

SendN can return a Results iterator while sending multiple HTTP requests. A consumer supplies yield, receives each Result as it arrives, and can print a progress bar in real time. The package can therefore expose a synchronous-looking API while concurrency remains an internal implementation detail. section 6.0 section 6.3.1

Listing 6.3 Implementing the Results iterator (hit/result.go)
package hit

import (
    "iter"  #1
    "time"
)

// Results is an iterator for [Result] values.
type Results iter.Seq[Result]  #2

. . .

Inspect the Results declaration, which aliases iter.Seq[Result] for the hit package. section 6.3.1

How Go by Example covers it

How deep it goes
Defines yield-based control flow and generic Go types, then applies them to Result production without detailing the complete implementation.
Examples
Uses SendN, Result values, concurrent HTTP requests, and a real-time progress bar as concrete applications.
What you can do after
Apply it via iter.Seq by returning values through a consumer-provided yield function that can stop iteration.
How it connects
Connects iterators with concurrency, channels, HTTP requests, and the pipeline pattern.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.