Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Iterator Pattern Implementation in Go

11 min readbeginner
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Iterator Pattern runs in O(n) time and O(1) space, in Go as in every other language.
  • ✓This is the one language on the page where the answer changed recently. For fifteen years Go had NO iterator protocol: you returned a slice, exposed a closure, or shipped values over a channel.
  • ✓On Go 1.23 or newer, return iter.Seq[V] for a lazy sequence and let callers range over it; use iter.Seq2[K, V] when an index or key travels with the value.
  • ✓The Go trap: The channel-based iterator that Go used for years leaks: if the consumer stops early, the producing goroutine blocks forever on its send and is never collected, so every abandoned iteration costs you a goroutine and everything it references, this is why range-over-func exists.
  • ✓range-over-func is a closure call per element, which the compiler can often inline for simple sequences but not always; it is slower than ranging a slice directly and dramatically faster than a channel, which costs a lock and a scheduler round-trip per item.

What Iterator Pattern actually is

The Iterator pattern gives you sequential access to the elements of a collection without exposing how that collection stores them, so a caller can walk a linked list, a tree, a database cursor or an infinite generated sequence through one uniform interface. The classic Gang of Four description is a pair of objects, an aggregate that can produce iterators and an iterator that holds the traversal position, but that framing badly understates what happened next: iteration is the one design pattern that got absorbed into the languages themselves. Six of the eight languages here have dedicated SYNTAX for producing an iterator (yield, function*, or a trait the for loop desugars to), one added it only in 2024 after fifteen years without it, and the meaningful engineering differences are laziness, whether a sequence can be walked twice, and what happens if you mutate the collection mid-walk.

Iterator Pattern in Go: what you actually reach for

This is the one language on the page where the answer changed recently. For fifteen years Go had NO iterator protocol: you returned a slice, exposed a closure, or shipped values over a channel. Go 1.23 (August 2024) added range-over-func, so a function of type iter.Seq[V] = func(yield func(V) bool) or iter.Seq2[K, V] can be used directly in a for...range loop, and the iter, slices and maps packages now supply Values, All, Collect, Sorted and friends built on it.

Go implementation

On Go 1.23 or newer, return iter.Seq[V] for a lazy sequence and let callers range over it; use iter.Seq2[K, V] when an index or key travels with the value. Always honour the boolean the yield function returns, false means the consumer broke out, and you must return immediately so deferred cleanup runs. On older Go, return a slice for small finite results and reserve channels for genuinely concurrent producers.
go
package ring

import "iter"

type Ring struct{ items []int }

// All is an iterator: Go 1.23+ can range over it directly.
func (r *Ring) All() iter.Seq[int] {
	return func(yield func(int) bool) {
		for _, n := range r.items {
			// yield returns false when the consumer breaks, stop NOW,
			// or deferred cleanup never runs.
			if !yield(n) {
				return
			}
		}
	}
}

// Seq2 carries the index alongside the value.
func (r *Ring) Indexed() iter.Seq2[int, int] {
	return func(yield func(int, int) bool) {
		for i, n := range r.items {
			if !yield(i, n) {
				return
			}
		}
	}
}

// Usage:
//   for n := range r.All()      { ... }
//   for i, n := range r.Indexed() { ... }
//
// The pre-1.23 channel idiom LEAKS a goroutine whenever the
// consumer breaks early, that is the reason this feature exists.

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Go-specific trap

The channel-based iterator that Go used for years leaks: if the consumer stops early, the producing goroutine blocks forever on its send and is never collected, so every abandoned iteration costs you a goroutine and everything it references, this is why range-over-func exists. With range-over-func the equivalent mistake is ignoring the yield return value and continuing to push after the consumer broke. And unrelated to either, ranging over a MAP is deliberately randomised in Go, so any test asserting map iteration order is flaky by construction.

Performance in Go, beyond the O(n)

range-over-func is a closure call per element, which the compiler can often inline for simple sequences but not always; it is slower than ranging a slice directly and dramatically faster than a channel, which costs a lock and a scheduler round-trip per item. The practical guidance: return a slice when the result is small and fully materialised, use iter.Seq when the sequence is large, lazy or expensive to produce, and use a channel only when the producer genuinely runs concurrently. The asymptotic cost is the same in every language, O(n) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Iterator Pattern between languages.

Real-World Applications

Iterator Pattern is used extensively in production software: framework internals, plugin architectures, state management libraries, and large-scale application architectures all rely on this pattern. In Go, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Iterator Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Iterator Pattern appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Iterator Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Iterator Pattern to build pattern recognition. In Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

Frequently Asked Questions

Which Go type or library should I use for Iterator Pattern?

This is the one language on the page where the answer changed recently. For fifteen years Go had NO iterator protocol: you returned a slice, exposed a closure, or shipped values over a channel. Go 1.23 (August 2024) added range-over-func, so a function of type iter.Seq[V] = func(yield func(V) bool) or iter.Seq2[K, V] can be used directly in a for...range loop, and the iter, slices and maps packages now supply Values, All, Collect, Sorted and friends built on it.

What is the most common Go mistake when implementing Iterator Pattern?

The channel-based iterator that Go used for years leaks: if the consumer stops early, the producing goroutine blocks forever on its send and is never collected, so every abandoned iteration costs you a goroutine and everything it references, this is why range-over-func exists. With range-over-func the equivalent mistake is ignoring the yield return value and continuing to push after the consumer broke. And unrelated to either, ranging over a MAP is deliberately randomised in Go, so any test asserting map iteration order is flaky by construction.

How does Iterator Pattern actually perform in Go?

range-over-func is a closure call per element, which the compiler can often inline for simple sequences but not always; it is slower than ranging a slice directly and dramatically faster than a channel, which costs a lock and a scheduler round-trip per item. The practical guidance: return a slice when the result is small and fully materialised, use iter.Seq when the sequence is large, lazy or expensive to produce, and use a channel only when the producer genuinely runs concurrently. Time complexity is O(n) and space is O(1).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Before paying for GitHub Copilot, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.