Home > Mobile >  Why can you assign a slice to an empty interface but not cast it to the same empty interface
Why can you assign a slice to an empty interface but not cast it to the same empty interface

Time:12-17

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

CodePudding user response:

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}
    

*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.

  • Related