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

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

interface conversion panic when method is not actually missing

问题

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

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

这是接口的蓝图:

  1. type ResultsetInterface interface {
  2. Init(string)
  3. CacheSet(context.Context) error
  4. CacheSetPart(context.Context, int) error
  5. CacheGet(context.Context, string) error
  6. Add(interface{})
  7. AddResultset(interface{})
  8. }

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

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

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

英文:

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.

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

This is the interface blueprint

  1. type ResultsetInterface interface {
  2. Init(string)
  3. CacheSet(context.Context) error
  4. CacheSetPart(context.Context, int) error
  5. CacheGet(context.Context, string) error
  6. Add(interface{})
  7. AddResultset(interface{})
  8. }

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

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

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:

确定