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条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容