dongzhuoxie1244 2014-08-01 08:16
浏览 280
已采纳

使用接口在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....

  • 写回答

2条回答 默认 最新

  • dongqi4085 2014-08-01 08:30
    关注

    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 (<kbd>play.golang.org</kbd>):

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站