Skip to content

Instantly share code, notes, and snippets.

@geoangelotti
Created January 15, 2024 15:53
Show Gist options
  • Save geoangelotti/a565cfd656c2a26593730e18bea06ba1 to your computer and use it in GitHub Desktop.
Save geoangelotti/a565cfd656c2a26593730e18bea06ba1 to your computer and use it in GitHub Desktop.
Go Cyclic Iterator
package main
import "fmt"
func main() {
slice := []string{"ena", "dyo"}
iterator := cyclicIterator(slice)
for i := 0; i < 10; i++ {
fmt.Println(iterator())
}
fmt.Println(slice)
}
func cyclicIterator(iterable []string) func() string {
i := 0
return func() string {
if i >= len(iterable) {
i = 0
}
item := iterable[i]
i++
return item
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment