For example, I have an interface{}
named a
, and I also have an reflect.Type
called elemType
. Now, I want to type assert a to elemType
, but a.(elemType)
can't be compiled successfully. How to fix it?
Sorry for my confusing expression. My meaning is that I get a type from a function, and I want to type assert an interface{} to this type, but this type is stored in a reflect.Type variable.
What I want to do is similar to the code below:
var a interface{}
//do something
func getType() reflect.Type {
var ret reflect.Type
//do something
return ret
}
targetType := getType()
result := a.(targetType)
Consider a standard type assertion in Go:
v := a.(typeName)
Here the compiler can determine the type of the variable v
at compile time, and make use of that knowledge when compiling any further statements involving the variable.
With your example of using a refltect.Type
variable in the assertion, it would be impossible to determine the type of v
, so the code could not be compiled.
If you need to check that a particular interface variable is of a particular type at runtime, you can still do that with the reflect
package. For example:
// if elemType is a normal type
if reflect.ValueOf(a).Type() == elemType {
fmt.Println("type matches")
}
// if elemType is an interface, can check if the value implements it
if reflect.ValueOf(a).Type().Implements(elemType) {
fmt.Println("value implements interface")
}
But you will need a concrete type to return back to standard variables. If you've only got a small selection of possible types, perhaps using a type switch might do what you want.