【问题标题】:"Cannot use myType as type interface{}"? I thought all types counted as interface{} in Go? [duplicate]“不能使用 myType 作为类型接口{}”?我认为 Go 中的所有类型都算作 interface{} 吗? [复制]
【发布时间】:2019-01-06 21:02:12
【问题描述】:

我正在尝试编写一个可以采用任何类型的函数(更具体地说,试图让它采用任何类型的 protobuffer,但如果必须,我会满足于更广泛的通用性)。根据我的阅读,似乎可以这样做:

func processSlice(mySlice []interface{}) void{
  // Do stuff in here
}

但是,当我尝试将它与一片 protos 一起使用时,我收到以下错误:

cannot use myProtoSlice (type []*MyProto) as type []interface{} in argument to processSlice

【问题讨论】:

  • []interface{} 不是interface{},它是一个特定类型(interface{} 类型的一个片段)。您必须将 []interface{} 传递给该函数,但该切片可以包含任何类型(或任何类型的混合)的值。
  • 尝试使用类似func processSlice(mySlice ...interface{}) void{ // Do stuff in here }

标签: generics go protocol-buffers


【解决方案1】:

正如错误清楚地描述的那样:

不能使用 myProtoSlice (type []*MyProto) 作为 type []interface{} in processSlice 的参数

接口的[]interface{}不是interface{}类型是不同的。 Golang 对类型很严格。

将接口切片更改为仅接口以包装您在函数中接收到的值。修改以下代码:

func processSlice(mySlice []interface{}) void{
  // Do stuff in here
}

传递一个接口

func processSlice(mySlice interface{}) void{
  // Do stuff in here
}

【讨论】:

    【解决方案2】:

    您不能将切片从一种类型的切片转换为另一种类型(因为您可以键入),这会很昂贵,并且他们认为最好强制您显式。

    简单地为您实际需要处理的每种切片类型编写函数可能会不那么痛苦(如果您知道类型并且数量不多的话)。

    【讨论】:

      猜你喜欢
      • 2018-09-30
      • 1970-01-01
      • 2017-11-04
      • 2019-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      相关资源
      最近更新 更多