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

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>
查看全部
dongliaoqiang8524
dongliaoqiang8524
2016/11/21 03:10
  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

4个回复