duan246558 2018-09-04 22:14
浏览 684

Golang不能将类型用作参数中的类型

I am new to Go language and I am trying to get familiar with interfaces and their assignability.

I am trying to pass an argument from a struct into a function which is imported from another package.

main.go package:

package main  

import {
  anotherPackage
}

type I1 interface {
  anotherPackage.I2
}

type T1 struct {
  *anotherPackage.S1
}

type T2 struct {
  variable1 T1
}

type T3 struct {
  variable2 T2
}

func handler() {
  var fromI I
  var input = T3{}

  template := fromI.ExportedFunction(input.T3.variable1)
}

func main() {
  handler()
}

anotherPackage.go package

package anotherPackage

type I2 interface {
  ExportedFunction(S1)
}

type S1 struct {
  Path string
  File string
}

type S2 struct {}

func (s2 *S2) ExportedFunction(s1 S1) {}

I keep getting an error:

cannot use input.T3.variable1 (type T1) as type anotherPackage.S1 in argument to fromI.ExportedFunction

  • 写回答

1条回答 默认 最新

  • doumenshi1475 2018-09-05 02:16
    关注

    You cannot do that in Go like other Object-oriented language because Go does not support polymorphism. How about using T1 interface as the parameter to ExportedFunction instead of S1. example https://play.golang.org/p/72hgbSwNkaS

    评论

报告相同问题?

悬赏问题

  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法