使用接口在GO中加载函数 [英] Function Over Loading in GO using interfaces

查看:158
本文介绍了使用接口在GO中加载函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主类型和一个子类型嵌入在其中。主类和子类实现了一个接口。

当我为接口类型变量分配一个'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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆