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.