FAQ
Hello Gophers!

I am wondering whats the point of interfaces which only define methods and
not also exported fields.

Consider following example:

package store



type Query struct {

  mongo bson.M

}



func NewQuery() *Query {

  return &Query{

   mongo: make(bson.M),

  }

}



func (q *Query) Id(id interface{}) {

  switch t := id.(type) {

  case string:

   if bson.IsObjectIdHex(t) {

    q.mongo["_id"] = bson.ObjectIdHex(t)

   }

  }

}



type CustomerQuery struct {

  *Query

}



func NewCustomerQuery() *CustomerQuery {

  return &CustomerQuery{

   Query: NewQuery(),

  }

}



func (q *CustomerQuery) Name(name string) {

  q.mongo["name"] = name

}





package store



type Store struct {

  session *mgo.Session

  database *mgo.Database

}



func NewStore(s *mgo.Session) *Store {

  return &Store{

   session: s,

   database: s.DB(""),

  }

}



func (s *Store) Find(q interface{}, models interface{}) error {

  m := GetMongoFieldByReflection(q)

   return s.database.C("foobar").Find(q).All(models)

}



As you see CustomerQuery "inherits" the `Id()` method from `Query` and
extends it with some `Name()` method. Using composition in this case saves
us from a lot of boiler plate.

However the downside I experienced is that we need heavy reflection to get
the field `customerQuery.Query.mongo` which is required by our database
driver.

Wouldn't in this case it be really nice if I could define an interface with
a `mongo` field?
I do not get the benefit why interfaces are only limited to methods. In my
opinion fields should be considered also as part of an api.

Bodo

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
For more options, visit https://groups.google.com/d/optout.

Search Discussions

  • Tamás Gulácsi at Aug 24, 2014 at 10:20 am
    2014. augusztus 24., vasárnap 12:05:57 UTC+2 időpontban [email protected]
    a következőt írta:
    Hello Gophers!

    I am wondering whats the point of interfaces which only define methods and
    not also exported fields.
    This has been questioned answered and already here:
    https://groups.google.com/forum/#!searchin/golang-nuts/interface$20methods/golang-nuts/ZJ5DEv_36S8/Pnbgq-NrDecJ

    Answer for your concrete problem: create a "Mongo()" method.

    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
    For more options, visit https://groups.google.com/d/optout.

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedAug 24, '14 at 10:06a
activeAug 24, '14 at 10:20a
posts2
users2
websitegolang.org

2 users in discussion

Tamás Gulácsi: 1 post I: 1 post

People

Translate

site design / logo © 2023 Grokbase