Hi again,
On Aug 29, 2:55 pm, Gustavo Niemeyer <
gust...@niemeyer.net> wrote:
> On Wed, Aug 29, 2012 at 3:47 PM, dpapathanasiou
>
> <
denis.papathanas...@gmail.com> wrote:
> > but since the result type is different in each statement, I'm not sure how I can do it w/o repeating
>
> func yourQuery(c *mgo.Collection, result interface{}) error
I should thank you for this; it wasn't quite what I needed, but it got
me thinking about the problem the right way.
For the record/FWIW, here's how I answered my original question (I see
that Alex Luya has been asking for something similar --
http://groups.google.com/group/mgo-users/msg/7e1f8488c5188c77?hl=en --
so perhaps this will be of use to him, or other people who search this
mailing list later).
I started by defining an all-purpose query function, using a higher-
order function:
func Search(database string, collection string, s
func(*mgo.Collection) error) error {
session, err := mgo.Dial("localhost")
defer session.Close()
if err != nil {
panic(err) // no, not really
}
c := session.DB(database).C(collection)
return s(c)
}
With this in place, I can create simpler functions for the specific
collection struct, and always be sure that I get a slice of the right
type of struct in return, e.g.:
func SearchPeople(query interface{}, result *[]Person) func(c
*mgo.Collection) error {
return func(c *mgo.Collection) error {
return c.Find(query).All(result)
}
}
and calling this from main() or wherever is just:
var result []Person
err := Search("mydb", "person", SearchPeople(bson.M{"lastName":
"Jones"}, &result))
if err != nil {
panic(err) // don't get too excited
}
The critical thing being I can iterate through the result slice and
each one is a Person struct that I can manipulate directly:
for _, p := range result {
fmt.Println(p.FirstName) // or do whatever else
}
So anyway, this *does* answer my original question, and I'm glad for
all your responses.
I'm sorry we ended the exchange the way we did yesterday; I don't know
if I just wasn't making myself clear before, or why we wound up
talking past each other at some point.