Created
December 14, 2024 13:09
-
-
Save LeoCBS/0ebe7cc5ffcc29ccb7004a76dd924234 to your computer and use it in GitHub Desktop.
Golang iterator example 1.23
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
// Seq is an iterator over sequences of individual values. | |
// When called as seq(yield), seq calls yield(v) for each value v | |
// in the sequence, stopping early if yield returns false. | |
// type Seq[V any] func(yield func(V) bool) | |
// our iterator function takes in a value and returns a func | |
// that takes in another func with a signature of `func(int) bool` | |
func Countdown(v int) func(func(int) bool) { | |
// next, we return a callback func which is typically | |
// called yield, but names like next could also be | |
// applicable | |
return func(yield func(int) bool) { | |
// we then start a for loop that iterates | |
for i := v; i >= 0; i-- { | |
// once we've finished looping | |
if !yield(i) { | |
// we then return and finish our iterations | |
return | |
} | |
} | |
} | |
} | |
func main() { | |
for x := range Countdown(10) { | |
fmt.Println(x) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
to understand more about iterators https://medium.com/eureka-engineering/a-look-at-iterators-in-go-f8e86062937c