Original post

I’m trying to understand a type assertion detail. The following:

type StringThing string
var a interface{} = StringThing("test")
x, ok := a.(StringThing)
fmt.Println(x, ok)      // "test true"
y, ok := a.(string)
fmt.Println(y, ok)      // " false"

and:

type ArrayThing []interface{}
var a interface{} = ArrayThing{"one",2}
x, ok := a.(ArrayThing)
fmt.Println(x, ok)      // "[one 2] true"
y, ok := a.([]interface{})
fmt.Println(y, ok)      // "[] false"

demonstrate the issue.

I’m not sure why the type assertions don’t match the underlying type definitions in these cases. I’m not arguing that there is incorrect behavior here, I just want to know the reasoning.

My current thinking is that these are type assertions, not type conversions and the specific type declarations are creating new, separate types, not macros for the underlying types. Thus the second assertion in each case fails.

That being said, the point of the assertion would seem to be that the compiler can assume something about the value (e.g. it is possible to iterate though an array of interface{} in each case) and in both cases the assumption would seem to be valid.