Created
January 5, 2026 03:26
-
-
Save zhangyoufu/6ecc6f875f5720e0c0f57eea0a5f7b63 to your computer and use it in GitHub Desktop.
itertools-like Cycle and Take in Go
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 "iter" | |
| func Cycle[T any](items []T) func(func(T) bool) { | |
| return func(yield func(T) bool) { | |
| for { | |
| for _, item := range items { | |
| if !yield(item) { | |
| return | |
| } | |
| } | |
| } | |
| } | |
| } | |
| func Take[T any](seq iter.Seq[T], n int) []T { | |
| out := make([]T, 0, n) | |
| for v := range seq { | |
| out = append(out, v) | |
| if len(out) == n { | |
| break | |
| } | |
| } | |
| return out | |
| } | |
| func getDummyString(pattern string, length int) string { | |
| if pattern == "" { | |
| panic("getDummyString: empty pattern") | |
| } | |
| return string(Take(Cycle([]rune(pattern)), length)) | |
| } | |
| func main() { | |
| println(getDummyString("0123456789ABCDEF", 20)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment