Skip to content

Instantly share code, notes, and snippets.

@buth
Last active May 2, 2024 05:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buth/d603a9b1e0b76f54d36f to your computer and use it in GitHub Desktop.
Save buth/d603a9b1e0b76f54d36f to your computer and use it in GitHub Desktop.
Generic Iterator interface and MongoDB implementation
package iterator
type Iterator interface {
Next() (value interface{}, done bool, err error)
}
package mongodb
type iter struct {
done, closed bool
iter *mgo.Iter
result func() interface{}
}
func (i *iter) Next() (interface{}, bool, error) {
if !i.done {
// Get a new instance.
r := i.result()
// Get the next value and return it.
i.done = !(i.iter.Next(r))
return r, i.done, nil
}
if !i.closed {
i.closed = true
if err := i.iter.Close(); err != nil {
return nil, true, err
}
}
return nil, true, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment