使用接口在GO中加载函数 [英] Function Over Loading in GO using interfaces
问题描述
我有一个主类型和一个子类型嵌入在其中。主类和子类实现了一个接口。
当我为接口类型变量分配一个'main type'变量并使用该接口变量调用实现的方法时,它调用main type实现而不是子类型。我需要调用子类型实现。
GO可以吗?我认为我的代码设计有一些问题。在这里我给出了一个示例代码来描述这个问题。
package main
importfmt
type interf interface {
typeCheck()
}
type maintype struct {
subtype
}
类型子类型struct {}
func(maintype)typeCheck(){
fmt.Println(这是打印在Main类型中的)
}
$ b func(子类型)typeCheck(){
fmt.Println(这是打印在子类型中)
}
func main(){
var intr interf
var maintp maintype
intr = maintp
intr.typeCheck()这是打印在主类型我需要这是打印在子类型
PlayGround: http://play.golang.org/p/ ut5XPiED75
请帮助....
你需要明确将嵌入式子类型分配给您的接口:
func main(){
var intr interf
var maintp maintype
intr = maintp.subtype //< ====
intr.typeCheck()
}
输出( play.golang.org
这是打印在子类型
文章 Go中的继承语义详细说明了为什么它不起作用,在类型嵌入和实现继承部分。
它的解决方案是类型替代通过接口
Go通过使用接口来完成类型替换。
接口允许我们定义抽象行为并拥有不同的类型可以满足这种行为。
它仍然尽管依赖于影响正确的子类型到接口变量。
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.
这篇关于使用接口在GO中加载函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!