Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading