interface - Go 界面中的设计决策{}

标签 interface go type-conversion

为什么 Go 不会自动转换:

package main

import "fmt"

type Any interface{} // Any is an empty interface
type X func(x Any) // X is a function that receives Any

func Y(x X) { // Y is a function that receives X
  x(1)
}

func test(v interface{}) { // test is not considered equal to X
  fmt.Println("called",v)
}

func main() {
  Y(test) // error: cannot use test (type func(interface {})) as type X in argument to Y
}

还有这个:

package main
import "fmt"

type Any interface{}

func X2(a Any) {
  X(a)
} 
func Y2(a interface{}) {
  X2(a) // this is OK
}

func X(a ...Any) {
  fmt.Println(a)
}
func Y(a ...interface{}) { // but this one not ok
  X(a...) // error: cannot use a (type []interface {}) as type []Any in argument to X
}

func main() {
  v := []int{1,2,3}
  X(v)
  Y(v)
}

我真的希望 interface{} 可以在任何东西(slicesmap)上重命名为 Any , func) 不仅仅是简单的类型

第二个问题是:有没有办法让它成为可能?

最佳答案

第一个是关于type conversion type identity ,你有一套规则。
在“Why can I type alias functions and use them without casting?”中查看更多信息

  • type Any interface{} 是命名类型
  • interface{} 是一个未命名的类型

它们的身份不同,不能用func(interface[})代替func(Any)


第二个由 golang faq 涵盖

我可以将 []T 转换为 []interface{} 吗?

Not directly, because they do not have the same representation in memory.
It is necessary to copy the elements individually to the destination slice. This example converts a slice of int to a slice of interface{}:

t := []int{1, 2, 3, 4}
s := make([]interface{}, len(t))
for i, v := range t {
    s[i] = v
}

有关内存表示的更多信息,请参见“what is the meaning of interface{} in golang?”:

interface

关于interface - Go 界面中的设计决策{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27310220/

相关文章:

json - golang 嵌套结构和映射

Python timedelta对象-strfdelta和deltafstr函数,用于timedelta🠞字符串🠞timedelta的转换

python - 为什么 int(float(str)) 工作但 int(str) 不工作

java - 接口(interface)的调用者是否(需要)对底层实现做出假设?

vb.net - 我可以覆盖接口(interface)属性吗?

matlab - 与父类(super class)和子类构造函数交互

c# - C# 中的选项卡式用户界面

go - 追加不适用于定义为结构类型 slice 的命名类型

go - COM 中的 UTF-16 字符串

java - Oracle:意外强制 RR 年份格式