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\n", sc.clone().getName())
fmt.Printf("-> %s\n", 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.