Created
January 15, 2024 15:53
-
-
Save geoangelotti/a565cfd656c2a26593730e18bea06ba1 to your computer and use it in GitHub Desktop.
Go Cyclic Iterator
This file contains 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" | |
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