Interface Go&x27中的设计决策;s接口{}

Interface Go&x27中的设计决策;s接口{},interface,go,type-conversion,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 i

为什么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{}
可以重命名为
Any
,而不仅仅是简单的类型

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

第一个问题是关于和的,你有一套规则。
有关详细信息,请参阅“”

  • 类型任何接口{}
    都是命名类型
  • 接口{}
    是未命名类型
它们的标识不同,不能使用
func(interface[})
代替
func(Any)


第二个是由

我能否将
[]T
转换为
[]接口{}
? 不是直接的,因为它们在内存中没有相同的表示形式
有必要将元素单独复制到目标切片。此示例将int切片转换为接口{}切片:

有关内存表示形式的详细信息,请参见“”:

第一个是关于和,您有一套规则。
有关详细信息,请参阅“”

  • 类型任何接口{}
    都是命名类型
  • 接口{}
    是未命名类型
它们的标识不同,不能使用
func(interface[})
代替
func(Any)


第二个是由

我能否将
[]T
转换为
[]接口{}
? 不是直接的,因为它们在内存中没有相同的表示形式
有必要将元素单独复制到目标切片。此示例将int切片转换为接口{}切片:

有关内存表示形式的详细信息,请参见“”:


非常好的答案+1.非常好的答案+1.在NamedNamed之间缺少隐式强制转换在这里可能会感到不方便。这确实意味着,如果您将文件大小和标志都传递为
int64
s,您可以声明
类型标志uint64
,以便在您意外交换它们时类型系统将捕获。缺少namedunnamed之间的隐式强制转换在这里可能会感到不方便。这确实意味着,如果您将文件大小和标志都传递为
int64
s,则可以声明
type flags uint64
,以便在您意外地交换它们时,类型系统将捕获它们。
t := []int{1, 2, 3, 4}
s := make([]interface{}, len(t))
for i, v := range t {
    s[i] = v
}