简体   繁体   English

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

[英]Golang cannot use type as type in argument

I am new to Go language and I am trying to get familiar with interfaces and their assignability. 我是Go语言的新手,我试图熟悉接口及其可分配性。

I am trying to pass an argument from a struct into a function which is imported from another package . 我试图将参数从struct传递到从另一个package导入的function中。

main.go package: main.go软件包:

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 anotherPackage.go软件包

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

You cannot do that in Go like other Object-oriented language because Go does not support polymorphism. 您不能像其他面向对象的语言那样在Go中执行此操作,因为Go不支持多态。 How about using T1 interface as the parameter to ExportedFunction instead of S1. 如何使用T1接口作为ExportedFunction而不是S1的参数。 example https://play.golang.org/p/72hgbSwNkaS 范例https://play.golang.org/p/72hgbSwNkaS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 golang中的类型不一致,无法使用 <Type> 如 <Type> - Inconsistent type in golang, cannot use <Type> as <Type> golang中类型不一致,无法使用<type>作为*类型</type> - Inconsistent type in golang, cannot use <Type> as *Type golang不能在sort.Sort的参数中使用type作为sort.Interface - golang cannot use type as type sort.Interface in argument to sort.Sort 缓冲区问题无法使用 <type> 作为http.NewRequest golang的参数中的io.Reader类型 - Buffer issue cannot use <type> as type io.Reader in argument to http.NewRequest golang 错误:无法使用参数([] string)作为参数中的string类型 - Go error: Cannot use argument (type []string) as type string in argument 不能在 function 的参数中使用数据(类型 [] 字符串)作为类型字符串 - Cannot use data (type []string) as type string in argument to function 不能在函数参数中使用true(类型bool)作为类型字符串 - cannot use true (type bool) as type string in function argument 不能在func的参数中使用子项(类型[] Child)作为类型[] Node - cannot use children (type []Child) as type []Node in argument to func 不能在返回参数中使用msgs(类型&lt;-chan _)作为类型chan _ - cannot use msgs (type <-chan _) as type chan _ in return argument 不能在函数参数中使用document [0](uint8类型)作为[] byte类型 - cannot use document[0] (type uint8) as type []byte in function argument
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM