liveBook · Manning

Yield function

As explained in Go by Example

A yield function is a consumer-provided callback that receives one iterator value and returns a boolean indicating whether iteration should continue.

A yield function is a consumer-provided callback that receives one iterator value and returns a boolean. A push iterator calls it for each value, continuing while it returns true and stopping when it returns false. section 6.3.1

With Go's iter.Seq type, the callback has the shape func(V) bool. For Result values, Results is equivalent to func(yield func(Result) bool). The iterator owns production; the consumer supplies the yield function. section 6.3.1

Use the return value to control consumption:

  • Return true to let the iterator push another value. section 6.3.1
  • Return false to stop production before all values are delivered. section 6.3.1
  • Breaking from a for-range loop causes the compiler-provided yield function to return false automatically. section 6.3.3

Consuming Results

SendN returns a Results iterator. A consumer can range over it with `for r := range results`; the compiler invokes the iterator and supplies a yield function that receives each Result. Summarize can therefore consume values without depending on whether they originated from a slice or channel. section 6.3.1 section 6.3.3

package iter  #1
type Seq[V any] func(yield func(V) bool)  #2

Inspect the standard Seq callback signature: a generic push iterator is a function accepting yield func(V) bool. section 6.3.1

How Go by Example covers it

How deep it goes
Defines the callback signature and control flow, then connects early stopping to compiler-supported for-range iteration.
Examples
Uses Results, SendN, Summarize, and for-range consumption to demonstrate callback-driven iteration.
What you can do after
Apply it via Go's for-range loop to consume iterator values and stop iteration early with break.
How it connects
Connects push iterators, iter.Seq, for-range loops, closures, and Result values.

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.