How to Implement the Iterator Pattern in Go

Implement Go's Iterator Pattern by returning an iter.Seq[T] function that yields values via a callback to enable memory-efficient streaming loops.

Implement the Iterator Pattern in Go by defining a function that returns an iter.Seq[T] and uses a yield callback to stream values one by one.

func Lines(s []byte) iter.Seq[[]byte] {
	return func(yield func([]byte) bool) {
		for len(s) > 0 {
			var line []byte
			if i := IndexByte(s, '\n'); i >= 0 {
				line, s = s[:i+1], s[i+1:]
			} else {
				line, s = s, nil
			}
			if !yield(line[:len(line):len(line)]) {
				return
			}
		}
	}
}

Use this iterator with a range loop to process items without allocating intermediate slices:

for line := range Lines(data) {
	fmt.Println(string(line))
}