How to work with an error like "the interface has no field or method"?

I want to write an abstraction for 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 Id method), which in itself is obvious.

Is this a completely wrong approach on my part or is there a simple solution that allows the compiler to “trust” that there will be an Id property at runtime in the passed structures.

+4
source share
1 answer

You can define an interface that 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 {

mgo#Collection.UpdateId() interface{}, Ider.

+4

Source: https://habr.com/ru/post/1547228/


All Articles