Go does not have built-in lazy sequences or iterators; you must implement them manually using a function that accepts a callback (yield function). Define a function returning a closure that iterates over your data and calls the callback for each item, returning false to stop iteration.
type Seq[T any] func(yield func(T) bool)
func OfSlice[T any](s []T) Seq[T] {
return func(yield func(T) bool) {
for _, v := range s {
if !yield(v) {
return
}
}
}
}
// Usage
for v := range OfSlice([]int{1, 2, 3}) {
fmt.Println(v)
}
Note: The standard library does not support for v := range iterator() syntax yet; you must call the iterator function directly with a loop body closure as shown in the OfSlice implementation logic, or use the range keyword only if you are using Go 1.23+ with the specific range-over-func feature enabled for your module version.