英文:
How to work around "type interface has no field or method" error?
问题
我想要为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)
}
在编译时,我得到了"model.Id undefined (interface{} has no field or method Id)"的错误,这是显而易见的。
这是我方面完全错误的方法,还是有一个简单的解决方法可以让编译器"相信"在运行时传递的结构体上会有一个Id属性?
英文:
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.
答案1
得分: 4
你可以定义一个声明了Id函数的接口:
type Ider interface {
Id() interface{}
}
如果你的模型实现了Ider接口,那么你的函数就会起作用:
func (m *Manager) Update(model Ider) error {
// 更新逻辑
}
考虑到mgo#Collection.UpdateId()
函数接受interface{}
类型参数,它将接受一个实现了Ider接口的对象。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论