Last active
May 2, 2024 05:38
-
-
Save buth/d603a9b1e0b76f54d36f to your computer and use it in GitHub Desktop.
Generic Iterator interface and MongoDB implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package iterator | |
type Iterator interface { | |
Next() (value interface{}, done bool, err error) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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