Back to feed
Dev.to
Dev.to
7/15/2026
The original title is: "Go Iterators (range-over-func): the yield contract and the traps"

The original title is: "Go Iterators (range-over-func): the yield contract and the traps"

Original: Go Iterators (range-over-func): the yield contract and the traps

Short summary

A deep dive into Go 1.23's range-over-func iterators covering the yield contract, cleanup on break, and iter.Pull leaks. The yield function returns false when the consumer stops, and ignoring that signal causes a runtime panic. Resource cleanup requires defer inside the iterator closure, and iter.Pull demands an explicit stop() call to avoid leaks. The post includes concrete code examples for each trap.

  • Every yield call must be guarded by if !yield(...) { return } or the runtime panics
  • Open resources inside the iterator closure so defer covers the break case
  • iter.Pull requires mandatory stop() to prevent goroutine leaks

Generated with AI, which can make mistakes.

Is this a good recommendation for you?

Comments

Failed to load comments. Please try again.

Explore more