Skip to content

Commit d7c3e93

Browse files
thediveogopherbot
authored andcommitted
iter: improve documentation with iterator example
In introducing iterators, package iter gives an example of how to use an iterator in a range-over-func loop, but currently does not give an example of what an iterator implementation might look like. This change adds the example of map.Keys() before the usage example. Additionally, it references to the Go blog for further examples, as well as the language spec about for-range loops. Fixes #70986 Change-Id: I7108d341d314d7de146b4c221700736c943a9f5d Reviewed-on: https://go-review.googlesource.com/c/go/+/638895 Reviewed-by: Cherry Mui <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Auto-Submit: Ian Lance Taylor <[email protected]>
1 parent cce75da commit d7c3e93

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

src/iter/iter.go

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,22 @@ or index-value pairs.
2828
Yield returns true if the iterator should continue with the next
2929
element in the sequence, false if it should stop.
3030
31-
Iterator functions are most often called by a range loop, as in:
31+
For instance, [maps.Keys] returns an iterator that produces the sequence
32+
of keys of the map m, implemented as follows:
33+
34+
func Keys[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[K] {
35+
return func(yield func(K) bool) {
36+
for k := range m {
37+
if !yield(k) {
38+
return
39+
}
40+
}
41+
}
42+
}
43+
44+
Further examples can be found in [The Go Blog: Range Over Function Types].
45+
46+
Iterator functions are most often called by a [range loop], as in:
3247
3348
func PrintAll[V any](seq iter.Seq[V]) {
3449
for v := range seq {
@@ -187,6 +202,9 @@ And then a client could delete boring values from the tree using:
187202
p.Delete()
188203
}
189204
}
205+
206+
[The Go Blog: Range Over Function Types]: https://go.dev/blog/range-functions
207+
[range loop]: https://go.dev/ref/spec#For_range
190208
*/
191209
package iter
192210

0 commit comments

Comments
 (0)