Typecast to a specific struct type by its string name

假如想象 提交于 2019-12-25 08:57:13

问题


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 is T.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!