Re:Iterator patterns in Go
by tux21b on Sunday September 08, 2013 @12:00AM
(#6347765)
The most obvious pattern, a simple for loop and a separate iterator type, is imho missing. Something like "for iter.Next() { fmt.Println(iter.Value()) }" is commonly used in Go and doesn't look that bad either...
[ Parent
| on HN ]
A notable use of this pattern is bufio.Scanner: http://golang.org/pkg/bufio/#Scanner
An example, scanning lines from standard input:
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
fmt.Println(s.Text())
}
if err := s.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}I'll buy that -- it's sort of mentioned in the post as an object-based wrapper around the closure version, except I listed the functions as HasNext() and Next(). More boilerplate for the iterator implementer, but I agree, it reads better for the caller.