...
1# iter
2
3Simple tools for container iteration
4
5# DESCRIPTION
6
7`iter` and its sub-packages provide a set of utilities to make it easy for
8providers of objects that are iteratable.
9
10For example, if your object is map-like and you want a way for users to
11iterate through all or specific keys in your object, all you need to do
12is to provide a function that iterates through the pairs that you want,
13and send them to a channel.
14
15Then you create an iterator from the channel, and pass the iterator to the
16user. The user can then safely iterate through all elements
17
18## Channel-based iterator
19
20Iterators pass its values via channels. Your implementation must provide a "source"
21that writes to this channel.
22
23```go
24func iterate(ch chan *mapiter.Pair) {
25 ch <- &mapiter.Pair{Key: "key1", Value: ...}
26 ch <- &mapiter.Pair{Key: "key2", Value: ...}
27 ...
28 // DO NOT forget to close the channel
29 close(ch)
30}
31
32ch := make(chan *mapiter.Pair)
33go iterate(ch)
34
35for iter := mapiter.New(ch); i.Next(ctx); {
36 pair := i.Pair()
37 ...
38}
39```
40
41## Convenience functions
42
43As long as an object implements the appropriate method, you can use the
44convenience functions
45
46```go
47fn := func(k string, v interface{}) error {
48 ...
49}
50
51mapiter.Walk(ctx, source, mapiter.VisitorFunc(fn))
52```
53
54There are also functions to convert map-like objects to a map, and array-like objects
55to an array/slice
56
57```go
58var l []string
59err := arrayiter.AsArray(ctx, obj, &l)
60
61var m map[string]int
62err := mapiter.AsMap(ctx, obj, &m)
63```
64
65## Iterate over native containers (map/array)
66
67```go
68m := make(map[...]...) // key and value may be any type
69
70for iter := mapiter.Iterate(ctx, m); iter.Next(ctx); {
71 ...
72}
73```
74
75```go
76s := make([]...) // element may be any type
77
78for iter := arrayiter.Iterate(ctx, s); iter.Next(ctx); {
79 ...
80}
81```
View as plain text