Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active May 29, 2025 13:41
Show Gist options
  • Save Integralist/38ade4cd75f1efe01acd0738d01470cd to your computer and use it in GitHub Desktop.
Save Integralist/38ade4cd75f1efe01acd0738d01470cd to your computer and use it in GitHub Desktop.
Go: 1.23 iter.Seq/iter.Seq2 iterators #go #iterator
// This code demonstrates how iterators work in Go.
// This particular example is contrived, but I wanted something simple enough to demonstrate the point.
package main
import (
"fmt"
"iter"
"strings"
)
// stringlines returns an iterator over lines in a string.
func stringlines(s string) iter.Seq[string] {
return func(yield func(string) bool) {
lines := strings.Split(s, "\n")
for _, line := range lines {
if !yield(line) { // Call yield with the current line
return // Stop if yield returns false
}
}
fmt.Println("yield() never returned false so the internal for loop kept going")
}
}
func main() {
data := "line one\nline two\nline three"
// function stringlines() returns an iterator:
for line := range stringlines(data) {
fmt.Println(line)
}
// Iterating with early exit:
// If the range 'block' returns/breaks, then that == false
// If the range 'block' completes, then that == true
for line := range stringlines(data) {
fmt.Println(line)
if line == "line two" {
break // exits the loop, signifying to yield() it should stop the loop inside of stringlines()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment