Retrieve from database using interface

291 views
Skip to first unread message

snore...@gmail.com

unread,
Feb 19, 2013, 10:43:36 AM2/19/13
to mgo-...@googlegroups.com
Hello,

I have following (untested) function:

func Execute(task MyInterface) {
    db := session.DB(task.Database()).C(task.Collection())
    var tasks []MyInterface
    db.Find(nil).All(&tasks)
    for _, t := range tasks { t.Do() }
}

I want to give my function a struct that implements interface MyInterface. It should then retrieve some values from mongodb and call a method on the retrieved structs.

Problem is "error: reflect.Set: value of type bson.M is not assignable to type mypkg.MyInterface" - is there some way to make this work? I tried to instantiate tasks using the type of the original struct, but couldn't get it working.

Any help would be appreciated - thanks :)

Jim Robinson

unread,
May 21, 2013, 9:19:09 AM5/21/13
to mgo-...@googlegroups.com
Two things I would think when looking at your post,
the first is to ask if you have you added bson Tags
to your structure, e.g., something like:

type Status struct {
Code int64      `bson:"_id"`
Type StatusType `bson:"type"`
Desc string     `bson:"desc"`
}

I think that as long as you've got it typed you ought
to be able to pass in the pointer to the slice as you
were attempting.

The second, since you seem to be simply looping
through the returned structures and calling a single
function, have you considered using the Iter.Next()
function instead of getting back a slice?

...
iter := session.Find(nil).Iter()

status := Status{}
for iter.Next(&status) {
        ... do something with status ...
}

err = iter.Close()
if err != nil {
        ...

Gustavo Niemeyer

unread,
May 21, 2013, 9:57:19 AM5/21/13
to mgo-...@googlegroups.com
On Tue, Feb 19, 2013 at 12:43 PM, <snore...@gmail.com> wrote:
> Problem is "error: reflect.Set: value of type bson.M is not assignable to
> type mypkg.MyInterface" - is there some way to make this work? I tried to
> instantiate tasks using the type of the original struct, but couldn't get it
> working.

You can't ask mgo to unmarshal onto an interface with methods because
there's no possible way for mgo to guess what the concrete type that
would satisfy such an interface is. You have to provide the concrete
value instead, which can itself satisfy an interface.


gustavo @ http://niemeyer.net

Jim Robinson

unread,
May 21, 2013, 10:48:25 AM5/21/13
to mgo-...@googlegroups.com
D'oh, I was completely glossing over the use of the word interface
when I read that post!  My apologies.
Reply all
Reply to author
Forward
0 new messages