Go Iteration tools with a rusty flavour
- Go 1.18+
- I missed some iteration style tools in Rust.
- Wanted to see how far I could push Go generics(turns out it is very limited).
- For fun.
package main
import (
"fmt"
"github.com/go-playground/itertools"
)
func main() {
results := itertools.WrapSlice([]int{4, 3, 2, 1, 0}).Iter().Filter(func(v int) bool {
if v >= 5 {
return true
}
return false
}).Collect()
fmt.Printf("%#v\n", results)
}See examples for more complex usages.
package main
import (
"fmt"
"github.com/go-playground/itertools"
optionext "github.com/go-playground/pkg/v5/values/option"
"strconv"
)
type FakeIterator struct {
max int
}
func (f *FakeIterator) Next() optionext.Option[int] {
f.max--
if f.max < 0 {
return optionext.None[int]()
}
return optionext.Some(f.max)
}
func main() {
results := itertools.WrapSliceMap[int, string]([]int{4, 3, 2, 1, 0}).Iter().Chain(&FakeIterator{
max: 10,
}).Filter(func(v int) bool {
if v >= 5 {
return true
}
return false
}).StepBy(2).Take(6).Map(func(v int) string {
return strconv.Itoa(v)
}).Iter().Collect()
fmt.Printf("%#v\n", results)
}Mapand it'sMAPtype parameter must be defined and passed around to be able to using inline. This is a limitation of Go generics not allowing new type parameters on methods.Chunkcan only be used at the end of a series of iterators fromIterbut can be used and wrapped byIteragain. This is a limitation of the Go Compiler which causes a recursive initialization issue golang/go#50215.Itermust be called on some types, like the wrapped slice or map types, to allow usage of helper functions tied directly to them but notIterateReducewill have to be used directly instead of other helper function such asSum,Product, ... again because no new type parameters on methods.
Make a pull request... can't guarantee it will be added, going to strictly vet what goes in.
Distributed under MIT License, please see license file within the code for more details.