如何解决”type interface has no field or method”错误?

huangapple go评论103阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年7月5日 14:16:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/24583607.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定