This question already has an answer here:
My Problem is as follows:
I have a slice of reflect.Value
, that was returned from a MethodByName("foo").Call()
.
now i want to cast the contained values to their types, which i dont know statically, but in form of relflect.Type
Basically what i want to do is:
values[0].Interface().(mytype)
but with reflection
values[0].Interface().(reflect.TypeOf(responseObject))
This gives me the compilation error:
reflect.TypeOf(responseObject) is not a type
Is there a way to do this in go?
Thanks and regards
BillDoor
</div>
What is a cast (type assertion)? It has two effects:
Obviously, #1 doesn't make sense for a type that is not known at compile-time, because how can the compile-time type of something depend on something not known at compile time?
You can still do manually do #2 for a type that is not known at compile time. Just get the runtime type of the value using reflect.TypeOf()
and compare it against the runtime.Type
you have.
If you have code using the normal type assertion syntax like:
x := v.(mytype)
Then the compiler knows that the variable x
is of type mytype
, and generates code accordingly. If the language let you use an expression in place of the type, then the compiler would have no way of knowing what type x
is, and consequently no way to generate code that uses that variable.
If you only know the type of value at runtime, then you will need to stick with the reflect.Value
API. You can determine the value's type using its Type
method, and there are methods that will let you access struct fields, indexes in slices or arrays, etc.
You will only be able to move back to regular syntax when you have a type you know about at compile time.