Go and custom struct type in another struct -


i'm struggling understand how save custom struct in struct (amongst great many other things). code looks this:

type dogs struct {   bleeh string   blaah string   bluuh string }  type stuff struct {   collection      *mgo.collection   //myanimalstruct type comes here? }  func newstuff(c *mgo.collection) *stuff {   return &stuff{     collection: c   } }  func getall(s *stuff) interface{} {   collection = s.collection   var results []dogs   err := collection.find(bson.m{}).all(&results)   if err != nil {     panic(err)   }   return results } 

now, rid of var results []dogs in getall function. instead, []dogs bit stuff struct somehow, can't figure out how.

this how call function:

func getmedogs(w http.responsewriter, r *http.request) interface{} {   collection = collection("animals")   s := newstuff(collection)   return getall(s) } 

so how s := newstuff(collection, dogs) stuff struct without declaring dog type in stuff (it anything, in function cats know...)?

the point want reuse getall function whatever other types, instead of making identical getall function of 63 animals. meow.

you can store prototypical value of type in stuff , use reflection create pointer value of type.

type stuff struct {     collection  *mgo.collection     v           interface{}   // prototype value }  func newstuff(c *mgo.collection, v interface{}) *stuff {     return &stuff{       collection: c,       v: v,     } }  func getall(s *stuff) (interface{}, error) {    p := reflect.new(reflect.typeof(s.v))    if err := s.collection.find(bson.m{}).all(p.interface()); err != nil {       return nil, err    }    return p.elem().interface(), nil } 

to construct dog collection:

s := newstuff(collection, []dog{}) 

some people reflection slow. that's true, in case cost small compared cost of executing find().all(). call find().all() sends request database server , waits response. response server unpacked using mgo's bson decoder. bson decoder makes heavy use of reflection.


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -