I have a "main type" and a "sub-type" is embedded in that.Both main and sub implements an interface.
When I'm assigning a 'main type' variable to interface type variable and call implemented method using that interface variable,It calls "main type" implementation not sub type's.I need to call sub-types implementation.
Is it possible in GO ? I think my code design is having some problem. Here I'm giving a sample code to describe this problem.
package main
import "fmt"
type interf interface{
typeCheck()
}
type maintype struct{
subtype
}
type subtype struct {}
func (maintype) typeCheck () {
fmt.Println("Hi,this is printed in Main type")
}
func (subtype) typeCheck () {
fmt.Println("Hi,this is printed in Sub-type")
}
func main() {
var intr interf
var maintp maintype
intr = maintp
intr.typeCheck()//Out :"Hi,this is printed in Main type" I need "Hi,this is printed in Sub-type"
}
PlayGround : http://play.golang.org/p/ut5XPiED75
Kindly Help....
You need to explicitly assign to your interface the embedded subtype:
func main() {
var intr interf
var maintp maintype
intr = maintp.subtype // <====
intr.typeCheck()
}
output (play.golang.org):
Hi,this is printed in Sub-type
The article "Inheritance Semantics in Go" details why it doesn't work, in the "Type Embedding and Implementation Inheritance" section.
Its solution is in "Type Substitution Through Interfaces"
Go accomplishes type substitution through the use of Interfaces.
Interfaces allow us to define an abstract behaviour and have different types satisfy that behaviour.
It still relies on affecting the right subtype to the interface variable though.
For example,
package main
import "fmt"
type interf interface {
typeCheck()
}
type subtype struct{}
func (subtype) typeCheck() {
fmt.Println("Hi,this is printed in Sub-type")
}
type maintype struct {
subtype
}
func (maintype) typeCheck() {
fmt.Println("Hi,this is printed in Main type")
}
func main() {
var intr interf
var maintp maintype
intr = maintp
// "Hi,this is printed in Main type"
intr.typeCheck()
// "Hi,this is printed in Sub-type"
intr.(maintype).subtype.typeCheck()
}
Output:
Hi,this is printed in Main type
Hi,this is printed in Sub-type