ProgramGuru

Introduction to Iterators

Start with Introduction to Iterators

An iterator defines how consumers visit a sequence without requiring all values to be stored in a slice first.

What you’ll learn

  • Explain the main purpose of introduction to iterators.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Go 1.23 introduced the iter package types iter.Seq[V] and iter.Seq2[K,V]. An iterator is a function that receives a yield callback and calls it for each item; returning false from yield tells the iterator to stop.

Iterators are often combined with range-over-function loops. They can generate values lazily and work with maps and slices adapters, though complexity and lifetime still matter.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for iteratorsThe producer chooses values; the consumer controls continuation.Create iter.SeqStep 1Start range loopStep 2Call yield(value)Step 3Stop at false or endStep 4The producer chooses values; the consumer controls continuation.
The producer chooses values; the consumer controls continuation.

Tools, syntax and practical notes

Requires Go 1.23 or later. Read the iter package documentation.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	"iter"
)

func countTo(limit int) iter.Seq[int] {
	return func(yield func(int) bool) {
		for n := 1; n <= limit; n++ {
			if !yield(n) {
				return
			}
		}
	}
}
func main() {
	for number := range countTo(4) {
		fmt.Println(number)
	}
}

Output

1
2
3
4

Trace what the program does

countTo returns an iterator function. The range loop invokes it, receives 1 through 4 and ends when the producer finishes.

Avoid common mistakes

  • Iterator implementations should honor a false return from yield.
  • A sequence does not guarantee a reusable or side-effect-free data source unless its contract does.

Try it yourself

Write an iterator that yields only even integers up to a given limit.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What signals an iterator to stop producing items?
Choose one answer. You can try again.

Answer and explanation

yield returns false

Correct. countTo returns an iterator function.

What you should remember

You have practiced Introduction to Iterators in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Range-Over-Function →