【问题标题】:Design decision in Go's interface{}Go 界面中的设计决策{}
【发布时间】:2014-12-05 06:38:16
【问题描述】:

为什么 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{} 可以在任何东西(slicesmapfunc)上重命名为 Any,而不仅仅是简单的类型

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

【问题讨论】:

  • namedunnamed 之间缺少隐式转换可能在这里感觉很不方便。这确实意味着,如果你将文件大小和标志都传递为int64s,你可以声明type Flags uint64,这样如果你不小心交换了它们,类型系统就会捕捉到。

标签: interface go type-conversion


【解决方案1】:

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

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

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


第二个被golang faq覆盖

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

不是直接的,因为它们在内存中的表示方式不同
有必要将元素单独复制到目标切片。此示例将 int 切片转换为 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?”:

【讨论】:

  • 非常好的答案+1。
猜你喜欢
  • 2017-09-20
  • 2011-03-04
  • 2014-02-25
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 2013-10-04
  • 2016-01-19
相关资源
最近更新 更多