Go界面中的设计决策{}

Kok*_*zzu 0 interface type-conversion go

为什么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
}
Run Code Online (Sandbox Code Playgroud)

还有这个:

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)
}
Run Code Online (Sandbox Code Playgroud)

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

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

Von*_*onC 5

第一个是关于类型转换和类型标识,您有一组规则.
查看更多在" 我为什么可以输入别名功能和使用,而不必铸造? "

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

他们的身份是不同的,你不能用来func(interface[})代替func(Any).


第二个是golang faq

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

不是直接的,因为它们在内存中没有相同的表示.
有必要将元素分别复制到目标切片.此示例将int切片转换为接口{}的切片:

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

有关内存表示的更多信息,请参阅" golang 的含义是interface{}什么? "

接口