globalsign / mgo

The MongoDB driver for Go
Other
1.97k stars 230 forks source link

Allow passing slice pointer as an interface pointer to Iter.All #181

Closed roobre closed 6 years ago

roobre commented 6 years ago

Sometimes we might encounter an scenario where the result holder used in Iter.All() is an slice passed down as an interface. For example:

func Fetch(path string, dest interface{}) {
    db.C(path).Find(nil).All(&dest)
}

func main() {
    // [...]
    Fetch("mycollection", make([]MyStruct, 0, 0))
}

In this scenario, mgo panics because dest is not a slice pointer. It actually is, but it's hidden as it is passed down as interface{} from Fetch(). We can simply check if the type behind the pointer is an interface, and if it is, just extract it again. That's what this patch does.

P.S.: Seems like gofmt also did some minor changes here and there, I hope you don't mind them.

domodwyer commented 6 years ago

Hi @roobre

Sounds like a good addition - can you add a test case that covers this behaviour? Also it seems changing the error message has broken the tests.

Dom

roobre commented 6 years ago

Woops, certainly didn't expect that.

I'll restore the log message for the original error and add cases for the new, hopefully this afternoon

domodwyer commented 6 years ago

Thanks, that's awesome!

Dom

domodwyer commented 6 years ago

Ah sorry, would you mind targeting the development branch?

We'll merge after, looks great!

Dom

roobre commented 6 years ago

Should I move the commits to the development branch or are you okay with merging master into develop?

roobre commented 6 years ago

Seems like some test timed out on MONGODB=x86_64-ubuntu1404-3.4.10.

domodwyer commented 6 years ago

Sorry yes, the tests are a bit flakey.

Thanks @roobre - really appreciate you taking the time to open a PR! I'll merge when the test is finished :)

Dom

roobre commented 6 years ago

No prob, thanks to you all for taking the time and effort of maintaining this project :D