Reputation: 15752
I want to write an abstraction to the mgo API:
package manager
import "labix.org/v2/mgo"
type Manager struct {
collection *mgo.Collection
}
func (m *Manager) Update(model interface{}) error {
return m.collection.UpdateId(model.Id, model)
}
When compiling I get "model.Id undefined (interface{} has no field or method Id)" which itself is obvious.
Is this a totally wrong approach from my side or is there an easy workaround how to let the compiler "trust" that there will be an Id property on runtime on passed structs.
Upvotes: 4
Views: 5486
Reputation: 1328522
You could defined an interface which declares an Id function
type Ider interface {
Id() interface{}
}
If your model is an Ider, then your function will work.
func (m *Manager) Update(model Ider) error {
Considering the mgo#Collection.UpdateId()
function takes interface{}
, it will accept an Ider
.
Upvotes: 4