函数使用接口在GO中重载

时间:2014-08-01 08:16:36

标签: go

我有一个"主要类型"和一个"子类型"嵌入在那里。主要和子实现一个接口。

当我分配一个'主要类型'变量到接口类型变量,并使用该接口变量调用实现的方法,它调用"主类型"实现不是子类型。我需要调用子类型实现。

GO可以吗?我认为我的代码设计存在一些问题。在这里,我提供了一个示例代码来描述这个问题。

  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

请帮助....

2 个答案:

答案 0 :(得分:4)

您需要明确地为您的界面指定嵌入的子类型:

func main() {
    var intr interf
    var maintp maintype
    intr = maintp.subtype  // <====
    intr.typeCheck()
}

输出( play.golang.org ):

Hi,this is printed in Sub-type

文章&#34; Inheritance Semantics in Go&#34;详细说明为什么它不起作用,在&#34;类型嵌入和实现继承&#34;节。
它的解决方案是在#34; Type Substitution Through Interfaces&#34;

  

通过使用Interfaces完成类型替换   接口允许我们定义抽象行为,并使不同的类型满足该行为。

它仍然依赖于影响接口变量的正确子类型。

答案 1 :(得分:2)

例如,

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()
}

输出:

Hi,this is printed in Main type
Hi,this is printed in Sub-type