Go 1.23 Iterators: Three yield Contract Traps That Cause Production Bugs
Go 1.23 introduced range-over-func iterators, allowing developers to range over custom functions using the iter.Seq and iter.Seq2 signatures from the iter package. The core mechanic relies on a yield function passed to the iterator, whose boolean return value signals whether the consumer wants to continue or has stopped via a break or return. A critical contract requires that iterators immediately stop and never call yield again once it returns false, or the runtime will panic. Iterators holding resources like files or database cursors must open them inside the closure and use defer to ensure cleanup even when a consumer exits early. A third pitfall involves iter.Pull, a pull-based adapter that can leak goroutines if its stop function is not explicitly called after use.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in