为什么可以将切片分配给空接口,但不能将其转换为相同的空接口?

huangapple go评论78阅读模式
英文:

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?

Example: https://play.golang.com/p/r4LXmR4JhF0

答案1

得分: 3

首先,Go语言根本不支持类型转换。

在Go中,根本没有类型转换的概念。

你尝试做的是类型断言。

你的尝试失败有两个原因,编译器已经解释了:

  1. invalid type assertion: slice.(<inter>) (non-interface type []interface {} on left)

    你不能将任何非接口类型断言为接口类型。

  2. non-name *castedSlice on left side of :=

    在这个上下文中,*castedSlice 是无效的。

如果你想将一个切片存储在类型为 interface{} 的变量中,赋值是正确的方法。你可以有几种方式实现:

  1. 如你已经发现的,这样可以工作:

    var result interface{}
    result = slice
    
  2. 你可以将这两行代码合并:

    var result interface{} = slice
    
  3. 你也可以使用短变量声明:

    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:

  1. invalid type assertion: slice.(<inter>) (non-interface type []interface {} on left)

    You cannot type-assert any non-interface type to an interface.

  2. 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:

  1. As you have discovered, this works:

    var result interface{}
    result = slice
    
  2. You can combine those two lines:

    var result interface{} = slice
    
  3. 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.

huangapple
  • 本文由 发表于 2021年12月16日 18:18:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/70377278.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定