问题
I would like to typecast a specific variable to a specific defined struct/interface by using the string name value of the struct/interface.
For example:
type Testing interface{}
and new variable
stringName := "Testing"
newTestingVariable.(stringName)
Is this possible by chance? Perhaps using reflection?
Cheers
回答1:
It is not possible. Go is a statically typed language, which means types of variables and expressions must be known at compile-time.
In a type assertion:
x.(T)
[...] If the type assertion holds, the value of the expression is the value stored in
x
and its type isT
.
So you use type assertion to get (or test for) a value of a type you specify.
When you would do:
stringName := "Testing"
newTestingVariable.(stringName)
What would be the type of the result of the type assertion? You didn't tell. You specified a string
value containing the type name, but this can only be decided at runtime. (Yes, in the above example the compiler could track the value as it is given as a constant value, but in the general case this is not possible at compile time.)
So at compile time the compiler could only use interface{}
as the type of the result of the type expression, but then what's the point?
If the point would be to dynamically test if x
's type is T
(or that if the interface value x
implements T
), you can use reflection for that (package reflect). In this case you would use a reflect.Type
to specify the type to be tested, instead of a string
representation of its name.
来源:https://stackoverflow.com/questions/47014890/typecast-to-a-specific-struct-type-by-its-string-name