Search code examples
gotype-assertion

Type assertion failed when using two different (but identical) types


I have this code

package main

import "fmt"

type MyType int

func main() {
    var i interface{} = 12

    f := i.(MyType)

    fmt.Println(f)
}

However, I get this error:

panic: interface conversion: interface is int, not main.MyType

However, int is, in this case, the same as MyType. Is there any way to do this without using the same type?


Solution

  • They're not identical types. As the runtime tells you, one is int and one is MyType. Go has a very specific definition of identical.

    Straight from the spec:

    A type declaration binds an identifier, the type name, to a new type that has the same underlying type as an existing type, and operations defined for the existing type are also defined for the new type. The new type is different from the existing type.

    https://golang.org/ref/spec#Type_identity

    https://golang.org/ref/spec#Type_declarations

    https://golang.org/ref/spec#Types

    You can easily convert between the two, MyType(12) works just fine, but type assertion is different from converting: https://golang.org/ref/spec#Type_assertions

    If you'd like to do some reading about interfaces and types and all of that fun stuff, these are both super helpful:

    http://blog.golang.org/laws-of-reflection

    http://research.swtch.com/interfaces