dongliaoqiang8524 2016-11-21 03:10
浏览 36
已采纳

在超类的子类上找不到接口方法[重复]

This question already has an answer here:

Given this code...

type BaseItf1 interface {
  getName() string
  clone() *BaseStruct
}

type BaseStruct struct {
  BaseItf1
}

func (bs *BaseStruct) cloneAndGetName() string {
  sc := bs.clone()
  return sc.getName()
}

type SubClass struct {
  BaseStruct
}

func (sc *SubClass) getName() string {
  return "A"
}

func (sc *SubClass) clone() *SubClass {
  return &SubClass{}
}

func main() {
  sc := &SubClass{}
  fmt.Printf("-> %s
", sc.clone().getName())
  fmt.Printf("-> %s
", sc.cloneAndGetName())
}

I can't quite figure out why I'm getting this error:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0x2004a]

The call to clone in main works perfectly, naturally.

In cloneAndGetName, however, the clone method can't be invoked. bs is typed to a pointer to BaseStruct, which has the BaseItf interface with the clone method. It would seem like the concrete sc instance in main that invoked cloneAndGetName knows how to locate the clone method.

What am I missing? Is there a better way to go about this? In my real code, I need a way to create a new instance of an object from some shared code.

</div>
  • 写回答

4条回答 默认 最新

  • douyuan4697 2016-11-21 04:30
    关注

    bs.clone() fails because it's trying to call bs.BaseItf1.clone() and bs.BaseItf1 is nil. You can't call the clone() defined for *SubClass from a variable of type *BaseStruct. Embedding types in Go is not the same as subclassing in other languages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗