Lots of things, but basically "it doesn't work that way". The thing inside the parentheses in a type assertion needs to be a type, that is a type name or a type literal. reflect.TypeOf(i)
isn't one of those, it's a method call expression. Therefore this is a syntax error. reflect.TypeOf doesn't "return a type" (which isn't really a thing you can do in Go), it returns a reflect.Type, which is an ordinary go struct that contains information about a type (i.e. sort of a meta-type).
But the more fundamental reason why it doesn't work is because it can't... Go needs to know what the type of a variable is when it's declared. Either its type is given explicitly in a var
declaration, or it's inferred from the type of the initialization value in a var x = value
declaration or x := value
short assignment. It is not possible for the type to be unknown at compile time. Go doesn't let you write an expression that produces an undetermined type.
The very purpose of a type assertion is to take a value of an interface type (which is a kind of "box" that can hold values of multiple types, or for interface{}
, any type at all) and retrieve a value of a specific concrete type. The value produced by the assertion will have the type named by the assertion, and no other. (In the case of a ,ok
assignment, if the assertion fails, the variable will hold a zero value but still be of the correct type). If you could write an assertion to a type that was known only at runtime, the whole thing would fall apart, so you can't write it — it's an error.
In short, you can't use reflection to do that. You can use reflect to learn what the type of i
is, you can learn that type's name, you can learn that its underlying Kind is Struct, you can enumerate the struct's fields and get the values out of them, etc... all of these are legitimate uses of reflection. But it can't give you back a variable of type MyStruct
— the way to do that is i.(MyStruct)
.