Re:Iterator patterns in Go
by zemo on Sunday September 08, 2013 @11:19AM
(#6348955)
Not a single solution has error handling. There actually exists a very good iterator pattern in the Mongo driver mgo. The idea is that you have some function Next, and Next takes a pointer. You pass a pointer into Next, and the iterator fills that address with some data, returning a boolean indicating success. Then you just put that in a for loop to loop over the whole thing. The whole thing, with error handling, looks like this:
http://godoc.org/labix.org/v2/mgo#Iter.Next
[ Parent
| on HN ]
For the vast majority of cases, I would expect panic/recover to work for iteration over in-memory data structures. For something like a database iterator where the possible errors are more varied and likely, I agree an explicit iterator object is better. I probably should have defined the scope of problems I was thinking about better.