I have an interface:
package pkg
type BaseInterface interface {
func Nifty() bool
func Other1()
func Other2()
...
func Other34123()
}
and a struct that implements it:
package pkg
type Impl struct {}
func (Impl) Nifty() bool { ... }
Then along comes another struct which wants to embed the first and do it's own Nifty():
package myOtherPackage
import "pkg"
type ImplToo struct {
*pkg.Impl
}
func (it ImplToo) Nifty() bool { ... something else ... }
This is sort of like class inheretance with method override in an OOP language. I want to know how to do the equivalent of implToo.super().Nifty() - that is, from the ImplToo Nifty() implementation, call the pkg.Impl Nifty() implementation.
What is the proper conversion to use on it
so that I can accomplish this? Everything I try yields either unbounded recursion on ImplToo's Nifty(), or some compiler error such as:
invalid type assertion: (&it).(BaseInterface) (non-interface type *it on left)
... or many variations on that.
You're looking for;
type ImplToo struct {
pkg.Impl
}
func (it ImplToo) Nifty() bool { return it.Impl.Nifty() }
Your use of pointers isn't consistent which is probably (not positive) part of your problem. If you want to make the embedded type a pointer then make your methods receiving type a pointer as well to avoid this problem.
If you want to explicitly use a method in the embedded type you reference it using the type where you would normally have a property name.
What @evanmcdonnal said. Your Nifty either need to take a pointer or not. If you embed the pointer to pkg.Impl
then your Nifty function needs to accept a struct pointer. If your Nifty function doesn't take a pointer then your embeded type should not be a pointer.
Here is an embedded pointer that works.
·> cat main.go
package main
import (
"cs/pkg"
"fmt"
)
type ImplToo struct {
*pkg.Impl
}
func (it *ImplToo) Nifty() bool {
fmt.Printf("Impl.Nifty() is %t
", it.Impl.Nifty())
return false
}
func main() {
i := new(ImplToo)
fmt.Println(i.Nifty())
}
·> cat cs/pkg/test.go
package pkg
type BaseInterface interface {
Nifty() bool
}
type Impl struct{}
func (i *Impl) Nifty() bool {
return true
}
Output:
Impl.Nifty() is true
false