https://github.com/lestrrat-go/iter
Iterator tools
https://github.com/lestrrat-go/iter
Last synced: 2 months ago
JSON representation
Iterator tools
- Host: GitHub
- URL: https://github.com/lestrrat-go/iter
- Owner: lestrrat-go
- License: mit
- Created: 2020-04-13T10:29:52.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2022-09-13T07:27:43.000Z (almost 3 years ago)
- Last Synced: 2024-06-18T18:50:20.895Z (about 1 year ago)
- Language: Go
- Size: 29.3 KB
- Stars: 8
- Watchers: 2
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Changelog: Changes
- License: LICENSE
Awesome Lists containing this project
README
# iter
Simple tools for container iteration
# DESCRIPTION
`iter` and its sub-packages provide a set of utilities to make it easy for
providers of objects that are iteratable.For example, if your object is map-like and you want a way for users to
iterate through all or specific keys in your object, all you need to do
is to provide a function that iterates through the pairs that you want,
and send them to a channel.Then you create an iterator from the channel, and pass the iterator to the
user. The user can then safely iterate through all elements## Channel-based iterator
Iterators pass its values via channels. Your implementation must provide a "source"
that writes to this channel.```go
func iterate(ch chan *mapiter.Pair) {
ch <- &mapiter.Pair{Key: "key1", Value: ...}
ch <- &mapiter.Pair{Key: "key2", Value: ...}
...
// DO NOT forget to close the channel
close(ch)
}ch := make(chan *mapiter.Pair)
go iterate(ch)for iter := mapiter.New(ch); i.Next(ctx); {
pair := i.Pair()
...
}
```## Convenience functions
As long as an object implements the appropriate method, you can use the
convenience functions```go
fn := func(k string, v interface{}) error {
...
}mapiter.Walk(ctx, source, mapiter.VisitorFunc(fn))
```There are also functions to convert map-like objects to a map, and array-like objects
to an array/slice```go
var l []string
err := arrayiter.AsArray(ctx, obj, &l)var m map[string]int
err := mapiter.AsMap(ctx, obj, &m)
```## Iterate over native containers (map/array)
```go
m := make(map[...]...) // key and value may be any typefor iter := mapiter.Iterate(ctx, m); iter.Next(ctx); {
...
}
``````go
s := make([]...) // element may be any typefor iter := arrayiter.Iterate(ctx, s); iter.Next(ctx); {
...
}
```