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 {



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

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.


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 golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Discussion Posts

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 1 of 2 | next ›
Discussion Overview
groupgolang-nuts @
postedAug 24, '14 at 10:06a
activeAug 24, '14 at 10:20a

2 users in discussion

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



site design / logo © 2022 Grokbase