Over function Download to GO using interfaces
I have a "main type" and a "subtype" built into it. The primary and secondary interface implements the interface.
When I assign a variable of type "main type" to an interface type variable and implement the invocation method using that interface variable, it calls the "main type" implementation, not the type sub.s. I need to call the implementation of subtypes.
Is this possible in GO? I think my code has some problems. Here I am giving 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
Please help ....
source to share
You need to explicitly assign an inline subtype to your interface:
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 " explains in detail why it doesn't work in the "Type Substitution and Injecting Inheritance" section. His solution is in "Type Substitution Through Interfaces"
Go does type substitution using interfaces.
Interfaces allow us to define abstract behavior and have different types that satisfy that behavior.
It still relies on the influence of the right subtype on the interface variable.
source to share
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
source to share