mirror of
https://github.com/golang/go.git
synced 2025-12-08 06:10:04 +00:00
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 <cherryyz@google.com> Reviewed-by: Ian Lance Taylor <iant@google.com> LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Auto-Submit: Ian Lance Taylor <iant@google.com>
This commit is contained in:
parent
cce75da30b
commit
d7c3e93c16
1 changed files with 19 additions and 1 deletions
|
|
@ -28,7 +28,22 @@ or index-value pairs.
|
||||||
Yield returns true if the iterator should continue with the next
|
Yield returns true if the iterator should continue with the next
|
||||||
element in the sequence, false if it should stop.
|
element in the sequence, false if it should stop.
|
||||||
|
|
||||||
Iterator functions are most often called by a range loop, as in:
|
For instance, [maps.Keys] returns an iterator that produces the sequence
|
||||||
|
of keys of the map m, implemented as follows:
|
||||||
|
|
||||||
|
func Keys[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[K] {
|
||||||
|
return func(yield func(K) bool) {
|
||||||
|
for k := range m {
|
||||||
|
if !yield(k) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Further examples can be found in [The Go Blog: Range Over Function Types].
|
||||||
|
|
||||||
|
Iterator functions are most often called by a [range loop], as in:
|
||||||
|
|
||||||
func PrintAll[V any](seq iter.Seq[V]) {
|
func PrintAll[V any](seq iter.Seq[V]) {
|
||||||
for v := range seq {
|
for v := range seq {
|
||||||
|
|
@ -187,6 +202,9 @@ And then a client could delete boring values from the tree using:
|
||||||
p.Delete()
|
p.Delete()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[The Go Blog: Range Over Function Types]: https://go.dev/blog/range-functions
|
||||||
|
[range loop]: https://go.dev/ref/spec#For_range
|
||||||
*/
|
*/
|
||||||
package iter
|
package iter
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue