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条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?