英文:
Why can you assign a slice to an empty interface but not cast it to the same empty interface
问题
为什么Golang不支持将切片转换为空接口?但是你可以通过声明一个类型为空接口的变量,并将切片赋值给该变量来绕过这个问题。为什么这两者不是同一回事呢?
示例:https://play.golang.com/p/r4LXmR4JhF0
英文:
Why does golang not support casting a slice to an empty interface? You can however work around it, by declaring a variable with an empty interface as type and assinging the slice to that variable. Why are those not the same thing?
答案1
得分: 3
首先,Go语言根本不支持类型转换。
在Go中,根本没有类型转换的概念。
你尝试做的是类型断言。
你的尝试失败有两个原因,编译器已经解释了:
-
invalid type assertion: slice.(<inter>) (non-interface type []interface {} on left)
你不能将任何非接口类型断言为接口类型。
-
non-name *castedSlice on left side of :=
在这个上下文中,
*castedSlice
是无效的。
如果你想将一个切片存储在类型为 interface{}
的变量中,赋值是正确的方法。你可以有几种方式实现:
-
如你已经发现的,这样可以工作:
var result interface{} result = slice
-
你可以将这两行代码合并:
var result interface{} = slice
-
你也可以使用短变量声明:
result := interface{}{slice}
*尽管有人可能会对这个说法挑剔:在Go中,通过使用unsafe
包,技术上可以实现与类型转换相同的功能,但由于这超出了语言规范,并且从定义上来说是不安全的,我认为说Go不支持类型转换仍然是合理的。
英文:
First, Go doesn't support casting at all.
There simply is no type casting in Go*.
What you're attempting to do is a type assertion.
There are two reasons your attempt fails. Both are explained by the compiler:
-
invalid type assertion: slice.(<inter>) (non-interface type []interface {} on left)
You cannot type-assert any non-interface type to an interface.
-
non-name *castedSlice on left side of :=
*castedSlice
is invalid in this context.
Assignment is the correct approach if you want to store a slice in a variable of type interface{}
. You can do this a few ways:
-
As you have discovered, this works:
var result interface{} result = slice
-
You can combine those two lines:
var result interface{} = slice
-
You can also do a short variable declaration:
result := interface{}{slice}
<hr>
*lest anyone nitpick the statement: It is technically possible to accomplish the same as type casting in Go, with use of the unsafe package, but as this is outside of the language spec, and is, by definition, unsafe, I think it's still a reasonable statement that Go does not support type casting.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论