接口转换恐慌当方法实际上不存在时

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

interface conversion panic when method is not actually missing

问题

在运行时,我得到了以下的panic消息,尽管在我看来,该方法已经正确地定义在实现该接口的结构体中。

panic: interface conversion: schema.MerchantResultset 
is not search.ResultsetInterface: missing method Add

这是接口的蓝图:

type ResultsetInterface interface {
	Init(string)
	CacheSet(context.Context) error
	CacheSetPart(context.Context, int) error
	CacheGet(context.Context, string) error
	Add(interface{})
	AddResultset(interface{})
}

以下是在运行时报告为缺失的方法,该方法被分配给了我的结构体MerchantResultset。

func (mr *MerchantResultset) Add(item interface{}) {
	mr.Data = append(mr.Data, item.(Merchant))
}

我对于实际需要的东西感到非常困惑。

英文:

Somehow, at runtime, I am getting the following panic message, even if it appears to me the method is properly defined to the struct that implements that interface.

panic: interface conversion: schema.MerchantResultset 
is not search.ResultsetInterface: missing method Add

This is the interface blueprint

type ResultsetInterface interface {
	Init(string)
	CacheSet(context.Context) error
	CacheSetPart(context.Context, int) error
	CacheGet(context.Context, string) error
	Add(interface{})
	AddResultset(interface{})
}

The following is the method that is reported missing during runtime, which is assigned to my struct MerchantResultset.

func (mr *MerchantResultset) Add(item interface{}) {
	mr.Data = append(mr.Data, item.(Merchant))
}

I am somehow very puzzled trying to understand what is actually being needed here

答案1

得分: 23

可能是因为你正在传递一个MerchantResultset,但Add方法只定义在该类型的指针上。

英文:

Probably it’s because you are passing around a MerchantResultset, but the Add method is only defined for a pointer to that type.

huangapple
  • 本文由 发表于 2016年4月10日 15:51:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/36527261.html
匿名

发表评论

匿名网友

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

确定